如果网站采用了无限级栏目结构,我们可以将网站所有栏目获取出来组成一个树形结构。
时隔一年,我发现这种写法确实很幼稚啊!Onethink的写法很好,建议大家看一下!
思路就是先一次性select查询,然后用一个函数转为树形数组!
--------------------------------------------------------------------------
数据库结构:
函数代码://获得指定文章分类的子分类组成的树形结构<br>
function cateTree($pid=0,$level=0){<br>
$cate=M('cate');<br>
$array=array();<br>
$tmp=$cate->where("pid='%d'",$pid)->select();<br>
if(is_array($tmp)){<br>
foreach($tmp as $v){<br>
$v['level']=$level;<br>
$array[count($array)]=$v;<br>
$sub=cateTree($v['id'],$level+1);<br>
if(is_array($sub))$array=array_merge($array,$sub);<br>
}<br>
}<br>
return $array;<br>
}
效果[print_r(cateTree(0))]:
Array
(
[0] => Array
(
[id] => 1
[catename] => 测试分类
[pid] => 0
[status] => 0
[level] => 0
)
[1] => Array
(
[id] => 5
[catename] => 二级分类
[pid] => 1
[status] => 0
[level] => 1
)
[2] => Array
(
[id] => 7
[catename] => 三级分类2
[pid] => 5
[status] => 0
[level] => 2
)
[3] => Array
(
[id] => 2
[catename] => 测试分类
[pid] => 0
[status] => 0
[level] => 0
)
[4] => Array
(
[id] => 4
[catename] => 又来测试
[pid] => 0
[status] => 0
[level] => 0
)
[5] => Array
(
[id] => 6
[catename] => 二级分类二
[pid] => 4
[status] => 0
[level] => 1
)
[6] => Array
(
[id] => 8
[catename] => 三级测试
[pid] => 6
[status] => 0
[level] => 2
)
)
其中level表示其层级。
格式化输出效果:
AD:真正免费,域名+虚机+企业邮箱=0元