无限级网站栏目-获取树形结构函数
程序员文章站
2024-02-03 23:44:22
...
如果网站采用了无限级栏目结构,我们可以将网站所有栏目获取出来组成一个树形结构。
时隔一年,我发现这种写法确实很幼稚啊!Onethink的写法很好,建议大家看一下!
思路就是先一次性select查询,然后用一个函数转为树形数组!
--------------------------------------------------------------------------
数据库结构:
函数代码:
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表示其层级。
格式化输出效果:
时隔一年,我发现这种写法确实很幼稚啊!Onethink的写法很好,建议大家看一下!
思路就是先一次性select查询,然后用一个函数转为树形数组!
--------------------------------------------------------------------------
数据库结构:
函数代码:
//获得指定文章分类的子分类组成的树形结构
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
)
)
其中level表示其层级。
格式化输出效果:
AD:真正免费,域名+虚机+企业邮箱=0元
推荐阅读