Thunderstriker Thunderstriker - 1 year ago 191
PHP Question

create array tree from array list

i have a list like this:

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:

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?

Answer Source

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]));

function createTree(&$list, $parent){
    $tree = array();
    foreach ($parent as $k=>$l){
            $l['children'] = createTree($list, $list[$l['id']]);
        $tree[] = $l;
    return $tree;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download