3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php function buildTree(array $elements, $parentId = '-1') { $branch = array(); foreach ($elements as $key => $value) { if ($value == $parentId) { $children = buildTree($elements, $key); $branch[$parentId] = $children; } } $branch[$parentId] = []; return $branch; } function recursivePrint($elements) { foreach ($elements as $key => $value) { echo 'count: '.count($value)."\n"; echo $key."\n"; recursivePrint($value); } } $childParent = ['0-1-2-3-4' => '-1', '0-1' => '-1', '3-4' => '0-1', '5-6' => '3-4', '5-6' => '01324']; $tree = buildTree($childParent); recursivePrint($tree);
based on Loh6F
Output for 5.6.0 - 5.6.30, hhvm-3.15.4, 7.0.0 - 7.3.0alpha1
count: 0 -1