3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?php $input = array( array('sn' => 1, 'name' => 'Clement', 'upper' => 0), array('sn' => 2, 'name' => 'Jean', 'upper' => 1), array('sn' => 3, 'name' => 'Annie', 'upper' => 1), array('sn' => 4, 'name' => 'Yuan', 'upper' => 2), array('sn' => 5, 'name' => 'Mei', 'upper' => 2), array('sn' => 6, 'name' => 'Blue', 'upper' => 3), array('sn' => 7, 'name' => 'Yang', 'upper' => 5), array('sn' => 8, 'name' => 'Lorinda', 'upper' => 0), ); $map = array(); foreach ($input as $node) { // init self if (!array_key_exists($node['sn'], $map)) { $map[$node['sn']] = array('self' => $node['name']); } else { $map[$node['sn']]['self'] = $node['name']; } // init parent if (!array_key_exists($node['upper'], $map)) { $map[$node['upper']] = array(); } // add to parent $map[$node['upper']][$node['sn']] = & $map[$node['sn']]; } print_r($map[0]);
Output for 4.3.0 - 5.6.29, hhvm-3.10.0 - 3.13.2, 7.0.0 - 7.1.0
Array ( [1] => Array ( [self] => Clement [2] => Array ( [self] => Jean [4] => Array ( [self] => Yuan ) [5] => Array ( [self] => Mei [7] => Array ( [self] => Yang ) ) ) [3] => Array ( [self] => Annie [6] => Array ( [self] => Blue ) ) ) [8] => Array ( [self] => Lorinda ) )