Skip to content

Instantly share code, notes, and snippets.

@jiromm
Last active December 3, 2018 14:09
Show Gist options
  • Save jiromm/a468b22cfba878a7aebeb48af67414f2 to your computer and use it in GitHub Desktop.
Save jiromm/a468b22cfba878a7aebeb48af67414f2 to your computer and use it in GitHub Desktop.
<?php
$list = [
[1, 2],
[2, 1],
[3, 1],
[4, 1],
[5, 2],
[6, 3],
[7, 3],
[8, 3],
[9, 4],
[10, 5],
[11, 5],
[12, 8],
[13, 8],
[14, 13],
[15, 14],
[16, 11],
[17, 16],
[18, 17],
];
$children = [];
foreach ($list as [$child, $parent]) {
if (!isset($children[$child])) {
$children[$child] = null;
}
$children[$parent][] = $child;
}
$children = merge($children);
print_r($children);
function merge($arr) {
$xarr = $arr;
foreach ($arr as $parent => $item) {
if (!is_array($item)) continue;
foreach ($item as $child) {
if (isset($arr[$child])) {
$arr[$parent] = array_unique(array_merge($arr[$parent], $arr[$child]));
}
}
}
if ($xarr != $arr) {
return merge($arr);
}
return $xarr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment