i have a list like this:
array( array(id=>100, parentid=>0, name=>'a'), array(id=>101, parentid=>100, name=>'a'), array(id=>102, parentid=>101, name=>'a'), array(id=>103, parentid=>101, name=>'a'), )
but way bigger so i need a efficient way to make this into a tree like structure like this:
array( id=>100, parentid=>0, name=>'a', children=>array( id=>101, parentid=>100, name=>'a', children=>array( id=>102, parentid=>101, name=>'a', id=>103, parentid=>101, name=>'a', ) ) )
i cannot use things like nested set or things like that becoas i can add left and right values in my database. any ideas?
oke this is how i solved it:
$arr = array( array('id'=>100, 'parentid'=>0, 'name'=>'a'), array('id'=>101, 'parentid'=>100, 'name'=>'a'), array('id'=>102, 'parentid'=>101, 'name'=>'a'), array('id'=>103, 'parentid'=>101, 'name'=>'a'), ); $new = array(); foreach ($arr as $a){ $new[$a['parentid']][] = $a; } $tree = createTree($new, array($arr[0])); print_r($tree); function createTree(&$list, $parent){ $tree = array(); foreach ($parent as $k=>$l){ if(isset($list[$l['id']])){ $l['children'] = createTree($list, $list[$l['id']]); } $tree[] = $l; } return $tree; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With