<?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);
You have javascript disabled. You will not be able to edit any code.