3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $array = [ [ 'id' => 1, 'title' => 'dir 1', 'parent_id' => 0, ], [ 'id' => 2, 'title' => 'dir 2', 'parent_id' => 0, ], [ 'id' => 3, 'title' => 'dir 3', 'parent_id' => 2, ], [ 'id' => 4, 'title' => 'dir 4', 'parent_id' => 3, ], [ 'id' => 5, 'title' => 'dir 5', 'parent_id' => 6, ], [ 'id' => 6, 'title' => 'dir 6', 'parent_id' => 0, ], ]; function build_tree($array, $parent_id = 0) { $result = []; foreach ($array as $item) { if ($item['parent_id'] == $parent_id) { $new_item = $item; $new_item['children'] = build_tree($array, $new_item['id']); $result[] = $new_item; } } return $result; } $tree = build_tree($array); print_r($tree);
Output for 5.6.0 - 5.6.30, hhvm-3.15.4, 7.0.0 - 7.3.0rc3
Array ( [0] => Array ( [id] => 1 [title] => dir 1 [parent_id] => 0 [children] => Array ( ) ) [1] => Array ( [id] => 2 [title] => dir 2 [parent_id] => 0 [children] => Array ( [0] => Array ( [id] => 3 [title] => dir 3 [parent_id] => 2 [children] => Array ( [0] => Array ( [id] => 4 [title] => dir 4 [parent_id] => 3 [children] => Array ( ) ) ) ) ) ) [2] => Array ( [id] => 6 [title] => dir 6 [parent_id] => 0 [children] => Array ( [0] => Array ( [id] => 5 [title] => dir 5 [parent_id] => 6 [children] => Array ( ) ) ) ) )