求助。php无限极分类。递归。咋数出来。每一个分类下面的小分类个数啊。希望有个demo谢谢!

【求助。php无限极分类。递归。咋数出来。每一个分类下面的小分类个数啊。希望有个demo谢谢!】 无限极分类存储时都是扁平,就是id和parent_id的关系,这时统计下级子分类不需要递归.
\u0026lt;?php$arr = array(\tarray(\u0026#39;id\u0026#39; =\u0026gt; 1212, \u0026#39;pid\u0026#39; =\u0026gt; 121, \u0026#39;name\u0026#39; =\u0026gt; \u0026#39;冷暖型\u0026#39;),\tarray(\u0026#39;id\u0026#39; =\u0026gt; 1211, \u0026#39;pid\u0026#39; =\u0026gt; 121, \u0026#39;name\u0026#39; =\u0026gt; \u0026#39;单冷型\u0026#39;),\tarray(\u0026#39;id\u0026#39; =\u0026gt; 122, \u0026#39;pid\u0026#39; =\u0026gt; 12, \u0026#39;name\u0026#39; =\u0026gt; \u0026#39;立柜式空调\u0026#39;),\tarray(\u0026#39;id\u0026#39; =\u0026gt; 121, \u0026#39;pid\u0026#39; =\u0026gt; 12, \u0026#39;name\u0026#39; =\u0026gt; \u0026#39;壁挂式空调\u0026#39;),\tarray(\u0026#39;id\u0026#39; =\u0026gt; 112, \u0026#39;pid\u0026#39; =\u0026gt; 11, \u0026#39;name\u0026#39; =\u0026gt; \u0026#39;双门\u0026#39;),\tarray(\u0026#39;id\u0026#39; =\u0026gt; 111, \u0026#39;pid\u0026#39; =\u0026gt; 11, \u0026#39;name\u0026#39; =\u0026gt; \u0026#39;单门\u0026#39;),\tarray(\u0026#39;id\u0026#39; =\u0026gt; 12, \u0026#39;pid\u0026#39; =\u0026gt; 1, \u0026#39;name\u0026#39; =\u0026gt; \u0026#39;空调\u0026#39;),\tarray(\u0026#39;id\u0026#39; =\u0026gt; 11, \u0026#39;pid\u0026#39; =\u0026gt; 1, \u0026#39;name\u0026#39; =\u0026gt; \u0026#39;冰箱\u0026#39;),\tarray(\u0026#39;id\u0026#39; =\u0026gt; 1, \u0026#39;pid\u0026#39; =\u0026gt; 0, \u0026#39;name\u0026#39; =\u0026gt; \u0026#39;家电\u0026#39;),);//pid即parent_id$pid = array();foreach($arr as $v) {\t$pid = $v;}//PHP从5.5开始可以用 array_column($arr, \u0026#39;pid\u0026#39;) 获取数组中指定的一列$tmp = array();foreach($arr as $v) {\t$i = 0;\tforeach($pid as $v1) {\t\tif($v === $v1) {\t\t\t$i++;\t\t\t$tmp] = $i;\t\t}\t}}var_export($tmp);//输出:array ( 121 =\u0026gt; 2, //id为121的下级分类有2个 12 =\u0026gt; 2, 11 =\u0026gt; 2, 1 =\u0026gt; 2,)
如果你需要根据扁平数据输出树形结构,才会用到递归:
\u0026lt;?phpfunction tree(array $arr, $pid = 0, $indent = \u0026#39;\u0026#39;) {\tforeach ($arr as $ele) {\t\tif ($ele === $pid) { //递归条件\t\t\t$indent2 = \u0026#39;__\u0026#39;.$indent;\t\t\techo $indent2.$ele.\u0026#39;:\u0026#39;.$ele."\";\t\t\ttree($arr, $ele, $indent2); //递归,把当前元素的ID作为父ID传参\t\t}\t}}tree($arr);//输出1:家电__12:空调____122:立柜式空调____121:壁挂式空调______1212:冷暖型______1211:单冷型__11:冰箱____112:双门____111:单门补充:
查询一个分类下的所有子分类,下面这篇文章可能对比有用.
MySQL无限分类数据结构:预排序遍历树算法http://www.cnblogs.com/alex2moro/archive/2013/01/03/2842637.html
求助。php无限极分类。递归。咋数出来。每一个分类下面的小分类个数啊。希望有个demo谢谢!


■网友
PHP无限级分类技术-慕课网


    推荐阅读