I have a bunch of objects tiered in an array, and want to recursively loop through them with PHP to add their corresponding tiers. How can I do that?
NOTE: The structure of the array could go much deeper than shown.
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
(
)
)
)
The problem is actually quite straight forward.
You need to iterate over each level of the structure, setting the tier, and when you encounter a node with children, recursively call the same function, but increment the tier value.
I used json_decode
to more easily create the stdClass
objects for the example, which you can see working here: 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;