kpesanka Posted October 16, 2007 Share Posted October 16, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/73514-solved-recursive-function-to-restructure-a-2d-array/ Share on other sites More sharing options...
sasa Posted October 16, 2007 Share Posted October 16, 2007 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); ?> Quote Link to comment https://forums.phpfreaks.com/topic/73514-solved-recursive-function-to-restructure-a-2d-array/#findComment-370935 Share on other sites More sharing options...
kpesanka Posted October 16, 2007 Author Share Posted October 16, 2007 It works perfectly - THANKS!!!!!!!!! Quote Link to comment https://forums.phpfreaks.com/topic/73514-solved-recursive-function-to-restructure-a-2d-array/#findComment-370958 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.