我有一堆对象分层在一个数组中,并希望用PHP递归循环它们以添加它们相应的层。我怎么能这样做?
注意:阵列的结构可能比显示的更深。
Array
(
[0] => stdClass Object //should be tier 1
(
[name] => Object name
[children] => Array
(
[0] => stdClass Object //should be tier 2
(
[name] => Object name
[children] => Array
(
[0] => stdClass Object //should be tier 3
(
[name] => Object name
[children] => Array
(
)
)
[1] => stdClass Object //should be tier 3
(
[name] => Object name
[children] => Array
(
)
)
)
)
[1] => stdClass Object //should be tier 2
(
[name] => Object name
[children] => Array
(
[0] => stdClass Object //should be tier 3
(
[name] => Object name
[children] => Array
(
)
)
)
)
)
)
[1] => stdClass Object //should be tier 1
(
[name] => Object name
[children] => Array
(
)
)
)
答案 0 :(得分:0)
这个问题实际上非常简单。
您需要迭代结构的每个级别,设置层,当遇到带子节点的节点时,递归调用相同的函数,但递增层值。
我使用json_decode
更轻松地为示例创建stdClass
个对象,您可以在此处查看:https://3v4l.org/oCJUV
<?php
function setTier(array $nodes, $tier = 1)
{
return array_map(function ($node) use ($tier) {
$node->tier = $tier;
$node->children = setTier($node->children, $tier + 1);
return $node;
}, $nodes);
}
$structure = json_decode('
[{
"name": "a",
"children": [{
"name": "c",
"children": [{
"name": "e",
"children": [{
"name": "g",
"children": []
}]
}, {
"name": "f",
"children": []
}]
}, {
"name": "d",
"children": [{
"name": "h",
"children": []
}]
}]
}, {
"name": "b",
"children": []
}]
');
$structure = setTier($structure);
print_r($structure); die;