-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask.php
37 lines (31 loc) · 956 Bytes
/
task.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
function testHierarchy(array $array): array
{
$result = [];
$links = [];
usort($array, static function($a, $b) {
if (!isset($a['parent_id'])) {
$a['parent_id'] = 0;
}
if (!isset($b['parent_id'])) {
$b['parent_id'] = 0;
}
return $a['parent_id'] <=> $b['parent_id'];
});
foreach ($array as $item) {
if (!isset($item['parent_id'])) {
$result[] = $item;
$links[$item['id']] = &$result[array_key_last($result)];
} else {
$parent_id = $item['parent_id'];
unset($item['parent_id']);
$parent = &$links[$parent_id];
if (!isset($parent['children'])) {
$parent['children'] = [];
}
$parent['children'][] = $item;
$links[$item['id']] = &$parent['children'][array_key_last($parent['children'])];
}
}
return $result;
}