[
[
'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 createTree($data, $levelKey, $childrenKey) {
$tree = [];
foreach ($data as $n) {
$arr = &$tree;
for ($level = $data[0][$levelKey]; $n[$levelKey] > $level; $level++) {
$arr = &$arr[count($arr) - 1][$childrenKey];
}
$arr[] = $n + [ $childrenKey => [] ];
}
return $tree;
}
$tree = createTree($data, 'depth', 'children');function createTree($data, $params = []) {
$levelKey = $params['levelKey'] ?? 'level';
$childrenKey = $params['childrenKey'] ?? 'children';
$root = [];
$parents = [ $data[0][$levelKey] => &$root ];
foreach ($data as $n) {
$n[$childrenKey] = [];
$level = $n[$levelKey];
$p = &$parents[$level];
$p[] = $n;
$parents[-~$level] = &$p[~-count($p)][$childrenKey];
}
return $root;
}
$tree = createTree($arr, [ 'levelKey' => 'depth' ]);