uidzer0b Posted October 19, 2007 Share Posted October 19, 2007 Hey everyone, I'm a long time lurker, first time poster I'm having a little trouble writing an algorithm to create a hierarchal structure from a database which looks like this: parent_id | child_id | ----------------+-------------+ 1 | 2 | 2 | 3 | 3 | 4 | 3 | 5 | 5 | 6 | 5 | 7 | So coming out of the database, I get an array which looks like this: Array ( [0] => Array ( [parent_id] => 1 [child_id] => 2 ) [1] => Array ( [parent_id] => 2 [child_id] => 3 ) [2] => Array ( [parent_id] => 3 [child_id] => 4 ) ... I would like to put this into an array which represents the following structure: 1 \ 2 \ 3 / \ 4 5 / \ 6 7 Can anyone point me in the right direction? Let me know if this isn't clear - I can try to elaborate. Thanks! Ben Quote Link to comment https://forums.phpfreaks.com/topic/73977-algorithm-help/ Share on other sites More sharing options...
Psycho Posted October 19, 2007 Share Posted October 19, 2007 Putting that data into an array in that manner will be problematic because you are going to end up with nothing but a bunch of arrays with null values. For example $array[1][2][3] must be an array because it has two child records (4 and 5). So $array[1][2][3][4] = ??? What exaclty are you planning to do with the array that you can't accomplish fro the data in the database? Quote Link to comment https://forums.phpfreaks.com/topic/73977-algorithm-help/#findComment-373413 Share on other sites More sharing options...
sasa Posted October 19, 2007 Share Posted October 19, 2007 try <?php $input = array( array('parent_id' => 1, 'child_id' => 2), array('parent_id' => 2, 'child_id' => 3), array('parent_id' => 3, 'child_id' => 4), array('parent_id' => 3, 'child_id' => 5), array('parent_id' => 5, 'child_id' => 6), array('parent_id' => 5, 'child_id' => 7) ); function my_tree($input, $start = false) { //find start node $p = array(); $c = array(); foreach ($input as $key => $v) { $p[$key] = $v['parent_id']; $c[$key] = $v['child_id']; } if ($start === false){ $start = array_diff($p,$c); $start = array_unique($start); } foreach ($start as $parent) { $keys = array_keys($p, $parent); $tmp = array(); foreach ($keys as $k) { $tmp1 = my_tree($input, array($c[$k])); echo ''; $tmp = array_merge($tmp, $tmp1); } if (count($tmp)==0) { $out[] = array('ID' => $parent); } else $out[]=array('ID' => $parent, 'CHILDs' => $tmp); } return $out; } $a = my_tree($input); print_r($a); ?> Quote Link to comment https://forums.phpfreaks.com/topic/73977-algorithm-help/#findComment-373459 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.