【发布时间】:2015-02-07 13:51:26
【问题描述】:
我正在研究一种算法来计算数组中的级别数量。
我需要这个的原因是因为我需要从数据库中获取属于类别父级的类别列表,并且根据该数组具有的级别数量,我需要显示一定数量的类别列表(到选择类别)。
所以这将是每个类别级别的类别列表,例如
Vehicles
Cars
honda
Red
Blue
Yellow
ford
Red
suzuki
Red
Green
BMW
Motorcycles
bla bla
bla bla
Groceries
Fruits
Berries
Red
Strawberries
所以我需要一个函数来检查所选父级的级别数量,例如,如果我传递车辆的 ID,如果我们将车辆计为级别 0,我希望它返回 4 或 3,所以我知道如果客户从第一个列表中选择了 Vechicles 我将不得不再显示 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;
}
}
我真的需要了解它是如何工作的,因为我必须使用像这样的几个函数,所以如果可以的话,请详细解释你的答案。
谢谢
【问题讨论】:
标签: php arrays algorithm categories