问题其实很简单。
您需要迭代结构的每个级别,设置层,当您遇到具有子节点的节点时,递归调用相同的函数,但增加层值。
我用过
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;