[英]Get lowermost level of php array
I have this array from prestashop: 我有来自prestashop的这个数组:
[11]=>
[id_category] => 11
[children] =>
[12]=>
[id_category] => 12
[children] =>
[13]=>
[id_category] => 14
I want get last level of this array that is the 13 array. 我想获得该数组的最后一级,即13个数组。 For get this array I use Category::getNestedCategories. 为了获得此数组,我使用Category :: getNestedCategories。
Try the following: 请尝试以下操作:
$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;
}
Now you can use it: 现在您可以使用它:
$max = findMaxDepth($tree);
Result will be 4 结果将是4
Try the below function:- 尝试以下功能:-
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;
}
Call it like findLowestChild($yourArray); 像findLowestChild($ yourArray);这样称呼它。 It will give you level value as well as the lowest value array. 它会为您提供级别值以及最小值数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.