如何在php中高效地从平面结构构建树?
阵列数据结构:如何在php中高效地从平面结构构建树?,php,algorithm,recursion,tree,Php,Algorithm,Recursion,Tree,阵列数据结构: id name parent_id children 现在我有了一个根数组和一组子数组,我想构建一个树结构,这就是我所拥有的: 更新:: function buildTree($root,$children) { foreach($children as $key=>$val){ print_r($val); $val['children']=array(); if($val['parent_i
id name parent_id children
现在我有了一个根数组和一组子数组,我想构建一个树结构,这就是我所拥有的:
更新::
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);
}
}
这将返回相同的根,而不是添加的子级
有人能帮我吗。非常感谢
更新:打印($val)打印输出:
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
)
.....
看起来$children数组以1开头,但“for”以0开头。请尝试更改函数以引用获取参数,如下所示:
function buildTree(&$root,&$children) {
否则,您将在每次调用中获得根/子数组的新副本,因此您将永远无法获得整个树
你会在手册中找到更多的信息:
如果你想要的是效率,你可能想考虑使用引用而不是递归,如这里所解释的:这将执行时间减少到不到1秒为什么你不在这里使用“foreach”($i=0;$iooo…)因为使用foreach,我不知道如何取消设置…我只是一个初学者:)@bingjie2680,你可以使用
foreach($arr as$key=>$val)
然后unset($arr[$key])
它似乎会把错误扫掉。但是整个函数返回相同的根,没有子项问题在$children
数组中。我猜它是空的。你能var\u dump($children)
把它贴在这里吗?