0

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?

Community
  • 1
  • 1
Jimmy
  • 373
  • 1
  • 16

1 Answers1

0

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...

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Tarsis
  • 712
  • 6
  • 14