3v4l.org

run code in 300+ PHP versions simultaneously
<?php function getTree(array $array) { $level = 0; $tree = []; $stack = [&$tree]; foreach($array as $item) { if($item['level']>$level) //expand stack for new items { //if there are child elements, add last to stack: $top = key($stack); if(count($stack[$top])) { end($stack[$top]); $stack[] = &$stack[$top][key($stack[$top])]; } //add ['children'] dim to top stack element end($stack); $top = key($stack); $stack[$top]['children'] = []; $stack[] = &$stack[$top]['children']; } while($item['level']<$level--) //pop till certain level { //two times: one for last pointer, one for ['children'] dim array_pop($stack); array_pop($stack); } //add item to stack top: end($stack); $stack[key($stack)][] = $item; $level = $item['level']; } return $tree; } $array = [ ['level'=>1, 'name' => 'Root #1'], ['level'=>1, 'name' => 'Root #2'], ['level'=>2, 'name' => 'subroot 2-1'], ['level'=>3, 'name' => '__subroot 2-1/1'], ['level'=>2, 'name' => 'subroot 2-2'], ['level'=>1, 'name' => 'Root #3'] ]; print_r(getTree($array));

preferences:
25.5 ms | 407 KiB | 5 Q