[
[
'depth' => 0,
'children' => []
],
[
'depth' => 1,
'children' => []
],
[
'depth' => 2,
'children' => []
],
[
'depth' => 3,
'children' => []
],
[
'depth' => 1,
'children' => []
],
[
'depth' => 0,
'children' => []
],
...
]
[
[
'depth' => 0,
'children' => [
[
'depth' => 1,
'children' => [
[
'depth' => 2,
'children' => [
[
'depth' => 3,
'children' => []
]
]
]
]
],
[
'depth' => 1,
'children' => []
]
]
],
[
'depth' => 0,
'children' => []
],
...
]
function makeTree($data, $levelField) {
$root = [];
foreach ($data as $d) {
$arr = &$root;
$level = 0;
while ($d[$levelField] > $level++) {
$arr = &$arr[count($arr) - 1]['children'];
}
$arr[] = array_merge($d, [ 'children' => [] ]);
}
return $root;
}
$tree = makeTree($data, 'depth');