thinkphp 实现无限分类
以上是效果图
1.数据库设计
2.添加后数据库的数据如下图
解析下:cid 栏目自增id
pid 栏目的父类id,id为0表示是顶级栏目
cat_name 栏目名称
path 表示栏目的层级关系
实现效果主要用到:
mysql的一个函数 concat():返回结果为连接参数产生的字符串
1,控制器的分类显示方法
public function fenlei (){ $cate =M( 'Category' ); $list = $cate ->field( "cid,cat_name,pid,path,concat(path,'-',cid) as bpath" )->order( 'bpath' )->select(); foreach ( $list as $key => $value ){ $list [ $key ][ 'count' ]= count ( explode ( '-' , $value [ 'bpath' ])); } $this ->assign( 'alist' , $list ); $this ->display(); }2,控制器的分类添加方法
public function addCat(){ $cate =D( 'Category' ); if ( $cate ->create()){ if ( $cate ->add()){ $this ->redirect( '/Test/fenlei' ); } else { $this ->error( '添加栏目失败' ); } } else { $this ->error( $cate ->getError()); } }3,栏目模型类
<?php class CategoryModel extends Model{ protected $_auto = array ( array ( 'path' , 'tclm' ,3, 'callback' ), ); function tclm(){ $pid =isset( $_POST [ 'pid' ])?(int) $_POST [ 'pid' ]:0; //echo ($pid); if ( $pid ==0){ $data =0; } else { $list = $this ->where( "cid=$pid" )->find(); $data = $list [ 'path' ]. '-' . $list [ 'cid' ]; //子类的path为父类的path加上父类的cid } return $data ; } } ?>4,主要的html代码
<body> <form action= "__URL__/addCat" method= "post" > <div style= "text-align:center;margin-top:80px;" > 请选择父类栏目:<select name= "pid" size= "20" style= "width:250px;" > <volist name= "alist" id= "v" > <option value= "{$v['cid']}" > < for start= "0" end = "$v['count']" > </ for > { $v [ 'cat_name' ]} </option> </volist> </select> <br/> 新的栏目名称:<input type= "text" name= "cat_name" style= "width:230px;" /><br/> <input type= "submit" value= "添加栏目" /> </div> </form> </body>查看更多关于thinkphp 实现无限分类 - Thinkphp的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did6477