3v4l.org

run code in 300+ PHP versions simultaneously
<?php $pages = array(); $pages[1] = array('id' => 1, 'parent' => 0, 'name' => 'Hello World'); $pages[2] = array('id' => 1, 'parent' => 1, 'name' => 'Child of Hello World'); $pages[3] = array('id' => 1, 'parent' => 0, 'name' => 'Brother of Hello World'); $pages[4] = array('id' => 4, 'parent' => 2, 'name' => 'Grand-child of Hello World'); $pages[6] = array('id' => 6, 'parent' => 4, 'name' => 'Great-grand-child of Hello World'); $children = array(); foreach($pages as $key => $page){ $parent = (int)$page['parent']; if(!isset($children[$parent])){ $children[$parent] = array(); $children[$parent][$key] = array('id' => $page['id'], 'name' => $page['name']); } } $new_pages = recursive_append_children($children[0], $children); function recursive_append_children($arr, $children){ foreach($arr as $key => $page) if(isset($children[$key])) $arr[$key]['children'] = recursive_append_children($children[$key], $children); return $arr; } print_r($new_pages);
Output for 7.1.25 - 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.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
Array ( [1] => Array ( [id] => 1 [name] => Hello World [children] => Array ( [2] => Array ( [id] => 1 [name] => Child of Hello World [children] => Array ( [4] => Array ( [id] => 4 [name] => Grand-child of Hello World [children] => Array ( [6] => Array ( [id] => 6 [name] => Great-grand-child of Hello World ) ) ) ) ) ) ) )
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Array ( [1] => Array ( [id] => 1 [name] => Hello World [children] => Array ( [2] => Array ( [id] => 1 [name] => Child of Hello World [children] => Array ( [4] => Array ( [id] => 4 [name] => Grand-child of Hello World [children] => Array ( [6] => Array ( [id] => 6 [name] => Great-grand-child of Hello World ) ) ) ) ) ) ) )

preferences:
146.85 ms | 405 KiB | 182 Q