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);

preferences:
30.18 ms | 402 KiB | 5 Q