Jump to content

[SOLVED] Recursive function to restructure a 2d array


kpesanka

Recommended Posts

I have a source array that looks like this:

 

array(

  array('ID'=>1, 'parentID'=>0),

  array('ID'=>2, 'parentID'=>1),

  array('ID'=>3, 'parentID'=>1)

)

 

Basically it is a bunch of ID/parentID pairs that indicate the relation of categories to their parent categories.

 

I need to create a recursive function to convert that array to one structured like this:

 

array(

  array('ID'=>1, 'children'=>array(

    array('ID'=>2),

    array('ID'=>3)

  )

)

 

The function should be recursive, because the sub-categories can go many levels deep. I want it structured like this so that I can easily traverse it later using another recursive php function (which is already written) and display the category tree using nested lists and such..

 

Any thoughts? I've been really struggling even trying to come up with a suitable base case. Any help will be very appreciated - I've been wracking my brains on this one and haven't yet come up with a solution.

try

<?php
function my_convert($a, $start = 0){
foreach ($a as $id) $tmp[$id['ID']] = $id[parentID];
return my_con($tmp, $start);
}
function my_con ($a, $start = 0){
$out = array();
$keys =  array_keys($a, $start);
foreach ($keys as $id) {
	$child = my_con($a, $id);
	if (count($child)) $out[] = array('ID' => $id, 'children' => $child); else $out[] = array('ID' => $id);
}
return $out;
}

$a = array(
  array('ID'=>1, 'parentID'=>0),
  array('ID'=>2, 'parentID'=>1),
  array('ID'=>3, 'parentID'=>1),
  array('ID'=>4, 'parentID'=>2),
  array('ID'=>5, 'parentID'=>2),
  array('ID'=>6, 'parentID'=>4)
);

$b = my_convert($a);
print_r($b);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.