如果网站采用了无限级栏目结构,我们可以将网站所有栏目获取出来组成一个树形结构。
数据库结构:
函数代码:
//获得指定文章分类的子分类组成的树形结构 function cateTree($pid=0,$level=0){ $cate=M('cate'); $array=array(); $tmp=$cate->where("pid='%d'",$pid)->select(); if(is_array($tmp)){ foreach($tmp as $v){ $v['level']=$level; $array[count($array)]=$v; $sub=cateTree($v['id'],$level+1); if(is_array($sub))$array=array_merge($array,$sub); } } return $array; }
复制代码
效果[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 ) )
方法仅供参考,有人说递归查询效率不好,其实在实际应用过程中我们可以把查询出来的内容放入缓存,然后修改栏目信息的时候更新缓存,不需要每次都来查询数据库。