gpt4 book ai didi

php - 在数组数组中查找级别数量的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:23:10 25 4
gpt4 key购买 nike

我正在研究一种算法来计算数组数组中的级别数量。

我需要这个的原因是因为我需要从数据库中获取属于父类别的类别列表,并且根据这个数组的级别数量,我需要显示一定数量的类别列表(以选择类别)。

因此这将是每个级别类别的类别列表,例如

Vehicles
Cars
honda
Red
Blue
Yellow
ford
Red
suzuki
Red
Green
BMW
Motorcycles
bla bla
bla bla
Groceries
Fruits
Berries
Red
Strawberries

所以我需要一个函数来检查所选父级的级别数量,例如,如果我传递车辆的 ID,我希望它返回 4 或 3 如果我们将车辆计为级别 0,那么我知道如果客户从第一个列表中选择了车辆,我将不得不再显示 3 个列表。

到目前为止,我所拥有的不起作用的是

function count_children_level($list_of_children, $start_depth = 0){    

// if the data being passed is an array
if(is_array($list_of_children)){

// amount of nodes is equal to the
$max = $start_depth;

foreach($list_of_children as $i){

$result = count_children_level($i, $start_depth + 1);

if ($result > $max){

$max = $result;
}
}
return $max;
}
//if is not array
else {
return $start_depth;
}
}

我真的需要了解它是如何工作的,因为我必须使用几个像这样的函数,所以如果可以的话,请详细解释你的答案。

谢谢

最佳答案

嵌套数组的深度等于其中最大数组的深度+1。

因此对于您的递归函数,您可以进行实际的递归调用,而不是每次都传递整个数组,只获取子数组的深度。因此,此函数为普通平面数组返回 1,为每个级别返回 1。

<?php
function array_depth($array) {
// Determine largest sub-array. Start with 0 if there are no arrays at all.
$max = 0;
foreach ($array as $item) {
if (is_array($item)) {
// Make the recursive call, passing not $array, but the sub-array ($item)
// to the function again.
$depth = array_depth($item);
if ($depth > $max)
$max = $depth;
}
}
// Depth of this array is the depth of the largest sub-array + 1.
return $max + 1;
}

我是这样调用它的:

echo array_depth(
array('x' =>
array('y' =>
array('z')))); // Returns 3.

关于php - 在数组数组中查找级别数量的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28382934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com