我正在研究算法以計算數組數組中的級別數量。查找數組中的級別數量的算法
我需要這個的原因是因爲我需要從屬於父類別的數據庫中獲取類別列表,並且根據此數組所具有的級別數量,我需要顯示一定數量的類別列表(選擇類別)。
因此,這將是對於類別中的各電平的類別列表,例如
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;
}
}
我真的需要理解它是如何工作的,因爲我有幾個功能,這樣的工作之一,所以請你,說明你的詳細回答。
感謝
嗨GolezTrol,非常感謝你的回答,你能不能請稍微解釋一下? – octohedron 2015-02-07 14:00:24
你可以發佈你使用的數組並將其添加到你的問題?我會檢查我的代碼,並在需要的地方修復它,或者解釋發生了什麼問題。 – GolezTrol 2015-02-07 14:13:09
你是對的,它按預期工作,但我傳遞的數組可能只有兩個級別,事情是我不需要知道數組的深度,但是類別的深度,因爲從數據庫中獲取的是什麼1級別的數組,具有在category_id和category_parent中指定的類別結構,所以它會比我想深入的要複雜得多 – octohedron 2015-02-07 14:15:39