我有来自prestashop的这个阵列:
[11]=>
[id_category] => 11
[children] =>
[12]=>
[id_category] => 12
[children] =>
[13]=>
[id_category] => 14
我想要获得该数组的最后一级,即13个数组。为了获得此数组,我使用Category :: getNestedCategories。
答案 0 :(得分:0)
尝试以下操作:
$tree = [
'id_category' => 11,
'children' => [
12 => [
'id_category' => 12,
'children' => [
13 => [
'id_category' => 13,
'children' => [
14 => [
'id_category' => 14
]
]
],
15 => [
'id_category' => 15
]
]
]
]
];
function findMaxDepth(array $data): int
{
$maxDepth = 0;
if (isset($data['children'])) {
// if there'are children of the node collect maxs on this level
foreach ($data['children'] as $child) {
// go on next level
$depth = findMaxDepth($child);
if ($maxDepth < $depth) {
$maxDepth = $depth;
}
}
}
return $maxDepth + 1;
}
现在您可以使用它:
$max = findMaxDepth($tree);
结果将为4
答案 1 :(得分:0)
尝试以下功能:-
function findLowestChild($arr, $level = 0, $lowestArr = ['level'=>0, 'value'=> null]){
if(isset($arr['children']) && is_array($arr['children'])) {
$level++;
foreach($arr['children'] as $childArr) {
$lowestArr = findLowestChild($childArr, $level, $lowestArr);
}
} else {
if($lowestArr['level'] < $level) {
$lowestArr['level'] = $level;
$lowestArr['value'] = $arr;
}
}
return $lowestArr;
}
像findLowestChild($ yourArray);一样调用它 它会为您提供级别值以及最小值数组。