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));
Output for git.master, git.master_jit, rfc.property-hooks
Array ( [children] => Array ( [0] => Array ( [level] => 1 [name] => Root #1 ) [1] => Array ( [level] => 1 [name] => Root #2 [children] => Array ( [0] => Array ( [level] => 2 [name] => subroot 2-1 [children] => Array ( [0] => Array ( [level] => 3 [name] => __subroot 2-1/1 ) ) ) [1] => Array ( [level] => 2 [name] => subroot 2-2 ) ) ) [2] => Array ( [level] => 1 [name] => Root #3 ) ) )

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:
44.79 ms | 404 KiB | 8 Q