3v4l.org

run code in 500+ PHP versions simultaneously
<?php $array = [ /* | */['id' => 1, 'depth' => 1], /* |----| */ ['id' => 19, 'depth' => 2], /* |----|----| */ ['id' => 20, 'depth' => 3], /* |----| */ ['id' => 73, 'depth' => 2], /* | */ ['id' => 3, 'depth' => 1], /* |----| */ ['id' => 25, 'depth' => 2], ]; $root = new stdClass(); $bread_crumbs = [$root]; foreach ($array as $item) { // make it object to simplify access to its parts $object_item = (object) $item; $expected_depth = count($bread_crumbs); if ($object_item->depth < 1) { throw new Exception('Depth cannot be lower than 1'); } elseif ($object_item->depth == $expected_depth) { // doing nothing } elseif ($object_item->depth < $expected_depth) { // remove 'unwanted' items to make expected_depth actual array_splice($bread_crumbs, -($expected_depth - $object_item->depth)); } else { throw new Exception('Error cannot jump too high'); } end($bread_crumbs)->children[] = $object_item; // and then just add to the end of bread_crumbs current object_item $bread_crumbs[] = $object_item; } var_dump($root);
Output for 5.4.0 - 5.4.45, 5.5.24 - 5.5.35, 5.6.8 - 5.6.28, 7.0.0 - 7.0.20, 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.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
object(stdClass)#1 (1) { ["children"]=> array(2) { [0]=> object(stdClass)#2 (3) { ["id"]=> int(1) ["depth"]=> int(1) ["children"]=> array(2) { [0]=> object(stdClass)#3 (3) { ["id"]=> int(19) ["depth"]=> int(2) ["children"]=> array(1) { [0]=> object(stdClass)#4 (2) { ["id"]=> int(20) ["depth"]=> int(3) } } } [1]=> object(stdClass)#5 (2) { ["id"]=> int(73) ["depth"]=> int(2) } } } [1]=> object(stdClass)#6 (3) { ["id"]=> int(3) ["depth"]=> int(1) ["children"]=> array(1) { [0]=> object(stdClass)#7 (2) { ["id"]=> int(25) ["depth"]=> int(2) } } } } }

preferences:
115.82 ms | 2156 KiB | 4 Q