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);
Output for rfc.property-hooks, git.master, git.master_jit
array(2) { [0]=> array(3) { ["id"]=> int(1) ["parent_id"]=> int(0) ["title"]=> string(10) "Category 1" } [2]=> array(4) { ["id"]=> int(2) ["parent_id"]=> int(0) ["title"]=> string(10) "Category 2" ["child"]=> array(1) { [0]=> array(4) { ["id"]=> int(3) ["parent_id"]=> int(2) ["title"]=> string(10) "Category 3" ["child"]=> array(1) { [0]=> array(3) { ["id"]=> int(4) ["parent_id"]=> int(3) ["title"]=> string(10) "Category 4" } } } } } }

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
48.46 ms | 1541 KiB | 4 Q