3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?php function getTree($array) { $level = 0; $tree = []; $stack = [uniqid(1) => &$tree]; //why uniqid? Try do debug without that :p 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[uniqid()] = &$stack[$top][key($stack[$top])]; } //add ['children'] dim to top stack element end($stack); $top = key($stack); $stack[$top]['children'] = []; $stack[uniqid(1)] = &$stack[$top]['children']; //add current item as a first child of top stack element end($stack); $top = key($stack); $stack[$top][] = $item; } elseif($item['level']<$level) //pop stack items till corresponding level { while($item['level']<$level--) { //two times: one for last pointer, one for ['children'] dim array_pop($stack); array_pop($stack); } end($stack); $stack[key($stack)][] = $item; } elseif($item['level']==$level) //add to current level { //just add since top stack element will be ['children'] dim $stack[key($stack)][] = $item; } end($stack); $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'] ]; echo('<pre>'); $result = getTree($array); print_r($result);
Output for 5.4.0 - 5.6.28, hhvm-3.10.0 - 3.12.0, 7.0.0 - 7.1.0
<pre>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 ) ) )
Output for 4.4.2 - 4.4.9, 5.1.0 - 5.3.29
Parse error: syntax error, unexpected '[' in /in/rKtco on line 5
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.4.1, 5.0.0 - 5.0.5
Parse error: parse error, unexpected '[' in /in/rKtco on line 5
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error in /in/rKtco on line 5
Process exited with code 255.