<?php
$links = [
[ 1, 3],
[ 3, 5],
[ 3, 7],
[ 3, 9],
[ 1, 10],
[10, 15],
];
$input = array_map(function ($link) {
return ['id' => $link[1], 'parent' => $link[0]];
}, $links);
function buildTreeMap($input, $child = 'id', $parent = 'parent') {
$map = array();
foreach ($input as $node) {
// init self
if (!array_key_exists($node[$child], $map)) {
$map[$node[$child]] = [];
}
// init parent
if (!array_key_exists($node[$parent], $map)) {
$map[$node[$parent]] = [];
}
// add to parent
$map[$node[$parent]][$node[$child]] =& $map[$node[$child]];
}
return $map;
}
$map = buildTreeMap($input);
// the whole map
print_r($map);
// only from root 1
print_r($map[1]);
preferences:
44.99 ms | 402 KiB | 5 Q