无限级分类在我们开发中显得举足轻重,会经常被人问到,而一般会用递归的方法来实现,但是递归又会难倒一批人。今天博主分享的这个稍微有点基础的phper都能学会,希望大家能喜欢。
一、先建立对应的数据库和表:
请注意pid和id的外键关联关系,最顶级的pid为0。
二、新建一个控制器,我就用默认的IndexController.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class
Tree{
//定义一个空的数组
static
public
$treeList
=
array
();
//接收$data二维数组,$pid默认为0,$level级别默认为1
static
public
function
tree(
$data
,
$pid
=0,
$level
= 1){
foreach
(
$data
as
$v
){
if
(
$v
[
'pid'
]==
$pid
){
$v
[
'level'
]=
$level
;
self::
$treeList
[]=
$v
;
//将结果装到$treeList中
self::tree(
$data
,
$v
[
'id'
],
$level
+1);
}
}
return
self::
$treeList
;
}
}
|
接下来方法中调用
1
2
3
4
5
6
|
public
function
index(){
$res
=M(
'cate'
)->select();
$res
=Tree::tree(
$res
);
$this
->cate=
$res
;
$this
->display();
}
|
三、前台模板页面中展示出来。
1
2
3
4
5
6
|
<
ul
>
<
volist
name
=
'cate'
id
=
'vo'
>
<!--这里加padding-left样式是为了更能看出层级的效果-->
<
li
style
=
"padding-left:{$vo['level']*20}px"
>{$vo.name}</
li
>
</
volist
>
</
ul
>
|
四、最终预览效果如下图所示:
到此,递归实现无限级分类的效果就实现了。
转载自:http://www.dawnfly.cn/article-1-235.html 破晓博客