如何在 php 中从扁平结构高效地构建树?
数组数据结构:
id name parent_id children
现在我有一个根数组和一组子数组,我想构建一个树结构,这就是我所拥有的:
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);
}
}
这返回相同的根, ,不添加儿童 有人可以帮我解决这个问题吗?多谢。
更新:print_r($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
)
.....
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
)
.....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试更改您的函数以通过引用获取参数,如下所示:
否则您将在每次调用中获得根/子数组的新副本,因此您将永远无法获得整个树。
您可以在手册中找到更多信息: http://www.php .net/manual/en/language.references.pass.php
Try to change you function to take the parameters by reference like so:
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
看起来你的 $children 数组以 1 开头,但你的“for”以 0 开头
looks like your $children array begins with 1, but your "for" begins with 0
如果您要求的是效率,您可能需要考虑使用引用而不是递归,如下所述:https://stackoverflow .com/a/34087813/2435335
这将执行时间减少到不到一秒
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