3v4l.org

run code in 300+ PHP versions simultaneously
<?php $menu = [ 0 => [ 'id' => 1, 'parent_id' => 0, 'title' => 'Category 1', ], 2 => [ 'id' => 2, 'parent_id' => 0, 'title' => 'Category 2', ], 3 => [ 'id' => 3, 'parent_id' => 2, 'title' => 'Category 3', ], 4 => [ 'id' => 4, 'parent_id' => 3, 'title' => 'Category 4', ] ]; function appendItem(array &$haystack, array $toAppend): void { foreach ($haystack as &$menuItem) { if ($menuItem['id'] === $toAppend['parent_id']) { if (array_key_exists('child', $menuItem)) { $menuItem['child'][] = $toAppend; } else { $menuItem['child'] = [$toAppend]; } return; } if (array_key_exists('child', $menuItem)) { appendItem($menuItem['child'], $toAppend); } } } foreach ($menu as $key => $menuItem) { if ($menuItem['parent_id'] !== 0) { unset($menu[$key]); appendItem($menu, $menuItem); } } var_dump($menu);

preferences:
42.97 ms | 1541 KiB | 5 Q