Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create array tree from array list

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?

like image 944
Thunderstriker Avatar asked Nov 16 '10 16:11

Thunderstriker


1 Answers

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; } 
like image 128
Thunderstriker Avatar answered Oct 14 '22 13:10

Thunderstriker