从子节点创建树 [英] Create tree from child node
本文介绍了从子节点创建树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个完整的数组包含以下项目:
I have got an array full with items like these:
array(
array(
'id' => 1,
'name' => 'parent 1',
'parent_id' => null
),
array(
'id' => 2,
'name' => 'child of parent 1',
'parent_id' => 1
),
array(
'id' => 3,
'name' => 'grand child of parent 1',
'parent_id' => 2
),
array(
'id' => 4,
'name' => 'parent 2',
'parent_id' => null
),
array(
'id' => 5,
'name' => 'child of parent 2',
'parent_id' => 4
),
);
我的问题是:我如何为已知的孩子建一棵树?例如,如果我知道id为3,我需要获得一系列项目,包括ID 1,2和3.
And my question is: How can i build a tree for a known child? For example if i know the id is 3, i need to get an array of items including ids 1,2 and 3.
谢谢。
推荐答案
也许是这样的:
function build($tab, $id)
{
$res = array();
$node = $tab[$id];
$i = 0;
do
{
$res[$i] = node;
$node = $tab[$node['parent_id']];
$i++;
} while( $node != null);
return $res;
}
这篇关于从子节点创建树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文