问题描述
我正在尝试设置一个可以有多个级别的列表,使用 parentId
来定义其父级.第一项的 parentId
为 NULL.一些条目的示例:
I'm trying to setup a list that can have multiple levels, using parentId
to define its parent. The first item's parentId
is NULL. Example of some entries:
id parentId name
1 NULL item1
2 NULL item2
3 1 item3
4 2 item4
5 3 item5
6 3 item6
所以,1和2是主项;3 是 1 的孩子;4 是 2 的孩子;5 是 3 的孩子(它本身就是 1 的孩子);6 也是 3 的孩子(它本身就是 1 的孩子);等
So, 1 and 2 are main items; 3 is a child of 1; 4 is a child of 2; 5 is a child of 3 (which is a child of 1 itself); 6 is also a child of 3 (which is a child of 1 itself); etc.
我一直在创建一个数组来正确地将这些项目添加到正确的级别.它应该是这样的:
I'm stuck creating an array that correctly adds these items to the right levels. It should look like this:
Array
(
[1] => Array
(
[name] => item1
[parentId] =>
[children] => Array
(
[3] => Array
(
[name] => item3
[parentId] => 1
[children] => Array
(
[5] => Array
(
[name] => item5
[parentId] => 3
)
[6] => Array
(
[name] => item6
[parentId] => 3
)
)
)
)
)
[2] => Array
(
[name] => item2
[parentId] =>
[children] => Array
(
[4] => Array
(
[name] => item4
[parentId] => 2
)
)
)
)
但是假设我使用 foreach()
浏览了所有项目,然后我到达了项目 5.它的 parentId 是 3,但在那时,我不知道这个 parent 3 位于何处在数组中,以及如何将子项添加到该父项.
But say I go through all the items using foreach()
, and I get to item 5. Its parentId is 3, but at that point, I have no idea where this parent 3 is located in the array, and how to add children to that parent.
有什么技巧可以遍历这些项目,并以正确的方式将它们全部放置到位吗?
Is there a trick to loop through these items, and put them all in place the right way?
推荐答案
这里
// your original data as an array
$data = array(
array(
'id' => 1,
'parentId' => null,
'name' => 'item1'
),
array(
'id' => 2,
'parentId' => null,
'name' => 'item2'
),
array(
'id' => 3,
'parentId' => 1,
'name' => 'item3'
),
array(
'id' => 4,
'parentId' => 2,
'name' => 'item4'
),
array(
'id' => 5,
'parentId' => 3,
'name' => 'item5'
),
array(
'id' => 6,
'parentId' => 3,
'name' => 'item6'
),
);
递归函数
function buildTree( $ar, $pid = null ) {
$op = array();
foreach( $ar as $item ) {
if( $item['parentId'] == $pid ) {
$op[$item['id']] = array(
'name' => $item['name'],
'parentId' => $item['parentId']
);
// using recursion
$children = buildTree( $ar, $item['id'] );
if( $children ) {
$op[$item['id']]['children'] = $children;
}
}
}
return $op;
}
print_r( buildTree( $data ) );
/*
Array
(
[1] => Array
(
[name] => item1
[parentId] =>
[children] => Array
(
[3] => Array
(
[name] => item3
[parentId] => 1
[children] => Array
(
[5] => Array
(
[name] => item5
[parentId] => 3
)
[6] => Array
(
[name] => item6
[parentId] => 3
)
)
)
)
)
[2] => Array
(
[name] => item2
[parentId] =>
[children] => Array
(
[4] => Array
(
[name] => item4
[parentId] => 2
)
)
)
)
*/
这篇关于在 PHP 中使用 parentIds 创建多级数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!