3

array data structure:

 id   name    parent_id   children

now I have a root array, and a set of array of children, I want to build a tree structure, and this is what I have:

Updated::

function buildTree($root,$children)
{   
    foreach($children as $key=>$val){
        print_r($val);
        $val['children']=array();
        if($val['parent_id']==$root['id']){
            $root['children'][]=$val;
            //remove it so we don't need to go through again
            unset($children[$key]);
        }
    }
    if(count($root['children'])==0)return;
    foreach($root['children'] as $child){
        $this->buildTree($child,$children);
    }
}

this returns the same root,,not children added could anybody helps me with this. thanks a lot.

update: print_r($val) print out:

 Array
(
[id] => 3
[name] => parent directory2
[type] => d
[creat_time] => 2011-07-08 06:38:36
[parent_id] => 1
[user_id] => 1
)
Array
(
[id] => 5
[name] => parent directory3
[type] => d
[creat_time] => 2011-07-08 06:38:36
[parent_id] => 1
[user_id] => 1
)
 .....
bingjie2680
  • 7,643
  • 8
  • 45
  • 72

3 Answers3

2

Try to change you function to take the parameters by reference like so:

function buildTree(&$root,&$children) {

otherwise you'll get a fresh copy of your root/children arrays in each call and therefore you'll never get the whole tree.

You'll find more information at the manual: http://www.php.net/manual/en/language.references.pass.php

towe75
  • 1,470
  • 10
  • 9
0

looks like your $children array begins with 1, but your "for" begins with 0

Greenisha
  • 1,417
  • 10
  • 14
-1

If efficiency is what you're asking for, you might want to consider using reference instead of recursion, as explained here: https://stackoverflow.com/a/34087813/2435335

This reduces hours of execution time to less than a second

Community
  • 1
  • 1
ntt
  • 426
  • 1
  • 4
  • 9