3v4l.org

run code in 300+ PHP versions simultaneously
<?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;
Output for 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.30, 8.2.0 - 8.2.25, 8.3.0 - 8.3.13
Array ( [0] => stdClass Object ( [name] => a [children] => Array ( [0] => stdClass Object ( [name] => c [children] => Array ( [0] => stdClass Object ( [name] => e [children] => Array ( [0] => stdClass Object ( [name] => g [children] => Array ( ) [tier] => 4 ) ) [tier] => 3 ) [1] => stdClass Object ( [name] => f [children] => Array ( ) [tier] => 3 ) ) [tier] => 2 ) [1] => stdClass Object ( [name] => d [children] => Array ( [0] => stdClass Object ( [name] => h [children] => Array ( ) [tier] => 3 ) ) [tier] => 2 ) ) [tier] => 1 ) [1] => stdClass Object ( [name] => b [children] => Array ( ) [tier] => 1 ) )

preferences:
67.55 ms | 418 KiB | 5 Q