thinkphp框架中使用递归实现无限级分类


无限级分类在我们开发中显得举足轻重,会经常被人问到,而一般会用递归的方法来实现,但是递归又会难倒一批人。今天博主分享的这个稍微有点基础的phper都能学会,希望大家能喜欢。

一、先建立对应的数据库和表:

无限级分类之mysql数据库表

请注意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  破晓博客


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM