Skip to content

Instantly share code, notes, and snippets.

@aristotle9
Last active November 13, 2015 08:22
Show Gist options
  • Save aristotle9/6169689aaf2b941df397 to your computer and use it in GitHub Desktop.
Save aristotle9/6169689aaf2b941df397 to your computer and use it in GitHub Desktop.
<?php
$a = [
2 => 1,
3 => 1,
4 => 1,
6 => 5,
7 => 5,
8 => 5,
9 => 7,
10 => 7,
11 => 10,
];
function trans($a) {
$pairs = [];
foreach ($a as $k => $v) {
if(isset($pairs[$v])) {
$pairs[$v] []= $k;
}
else {
$pairs[$v] = [$k];
}
}
$root_ids = array_diff(array_unique(array_values($a)), array_keys($a));
return build($root_ids, $pairs);
}
function build(&$ids, &$pairs) {
return array_map(function($id) use ($pairs) {
$item = ['id' => $id];
if(isset($pairs[$id])) {
$item['items'] = build($pairs[$id], $pairs);
}
return $item;
}, $ids);
}
$b = trans($a);
print_r($b);
echo json_encode($b, JSON_PRETTY_PRINT) . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment