bingjie2680
bingjie2680

Reputation: 7773

How to efficiently build a tree from a flat structure in php?

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
)
 .....

Upvotes: 3

Views: 1509

Answers (3)

ntt
ntt

Reputation: 436

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

Upvotes: -1

towe75
towe75

Reputation: 1470

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

Upvotes: 2

Greenisha
Greenisha

Reputation: 1437

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

Upvotes: 0

Related Questions