標籤:

求助。php無限極分類。遞歸。怎麼數出來。每一個分類下面的小分類個數啊。希望有個demo?謝謝!?


無限極分類存儲時都是扁平,就是id和parent_id的關係,這時統計下級子分類不需要遞歸.

& 1212, "pid" =&> 121, "name" =&> "冷暖型"),
array("id" =&> 1211, "pid" =&> 121, "name" =&> "單冷型"),
array("id" =&> 122, "pid" =&> 12, "name" =&> "立櫃式空調"),
array("id" =&> 121, "pid" =&> 12, "name" =&> "壁掛式空調"),
array("id" =&> 112, "pid" =&> 11, "name" =&> "雙門"),
array("id" =&> 111, "pid" =&> 11, "name" =&> "單門"),
array("id" =&> 12, "pid" =&> 1, "name" =&> "空調"),
array("id" =&> 11, "pid" =&> 1, "name" =&> "冰箱"),
array("id" =&> 1, "pid" =&> 0, "name" =&> "家電"),
);

//pid即parent_id
$pid = array();
foreach($arr as $v) {
$pid[] = $v["pid"];
}
//PHP從5.5開始可以用 array_column($arr, "pid") 獲取數組中指定的一列

$tmp = array();
foreach($arr as $v) {
$i = 0;
foreach($pid as $v1) {
if($v["id"] === $v1) {
$i++;
$tmp[$v["id"]] = $i;
}
}
}
var_export($tmp);
//輸出:
array (
121 =&> 2, //id為121的下級分類有2個
12 =&> 2,
11 =&> 2,
1 =&> 2,
)

如果你需要根據扁平數據輸出樹形結構,才會用到遞歸:

&

補充:

查詢一個分類下的所有子分類,下面這篇文章可能對比有用.

MySQL無限分類數據結構:預排序遍歷樹演算法
http://www.cnblogs.com/alex2moro/archive/2013/01/03/2842637.html


PHP無限級分類技術-慕課網


推薦閱讀:

怎樣深入學習php,成為php高手?

TAG:PHP | 遞歸 |