Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Currently I'm working on create multidimensional array for categories - subcategories relation and creating a JSON structure.

I have found the following code from following URL:

PHP Create a Multidimensional Array from an array with relational data

function makeRecursive($d, $r = 0, $pk = 'parent', $k = 'id', $c = 'children') {
  $m = array();
  foreach ($d as $e) {
    isset($m[$e[$pk]]) ?: $m[$e[$pk]] = array();
    isset($m[$e[$k]]) ?: $m[$e[$k]] = array();
    $m[$e[$pk]][] = array_merge($e, array($c => &$m[$e[$k]]));
  }

  return $m[$r][0];
}

echo json_encode(makeRecursive(array(
  array('id' => 5273, 'parent' => 0,    'name' => 'John Doe'),  
  array('id' => 6032, 'parent' => 5273, 'name' => 'Sally Smith'),
  array('id' => 6034, 'parent' => 6032, 'name' => 'Mike Jones'),
  array('id' => 6035, 'parent' => 6034, 'name' => 'Jason Williams'),
  array('id' => 6036, 'parent' => 5273, 'name' => 'Sara Johnson'),
  array('id' => 6037, 'parent' => 5273, 'name' => 'Dave Wilson'),
  array('id' => 6038, 'parent' => 6037, 'name' => 'Amy Martin'),
)));

This work well for the above array but its not working for multiple parent categories.check the following array which have two parent categories id : 5273 and 5274.

echo json_encode(makeRecursive(array(
      array('id' => 5273, 'parent' => 0,    'name' => 'John Doe'),
      array('id' => 5274, 'parent' => 0,    'name' => 'Kevin smith'),
      array('id' => 5276, 'parent' => 5274, 'name' => 'Ricky martin'),  
      array('id' => 6032, 'parent' => 5273, 'name' => 'Sally Smith'),
      array('id' => 6034, 'parent' => 6032, 'name' => 'Mike Jones'),
      array('id' => 6035, 'parent' => 6034, 'name' => 'Jason Williams'),
      array('id' => 6036, 'parent' => 5273, 'name' => 'Sara Johnson'),
      array('id' => 6037, 'parent' => 5273, 'name' => 'Dave Wilson'),
      array('id' => 6038, 'parent' => 6037, 'name' => 'Amy Martin'),
    )));

Does anybody have the solution?

share|improve this question

1 Answer 1

Well the used makeRecursive() function just does not work for data with more than a single root.

You could fix this but I think the more interesting question is in which form your original data is and if there could be a more elegant way to do the task. Maybe there is a easy way to do it with a real recursive function...

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.