无限极分类经常会用到,以下是一个案例,供大家参考:
知识点:
1、递归
2、PHP str_repeat(string,repeat) 函数把字符串重复指定的次数。
3、PHP unlink() 函数 unlink() 函数删除文件。
4、PHP file_exists() 函数 file_exists() 函数检查文件或目录是否存在。
扩展类:Catetree.php
<?php namespace catetree; class Catetree{ public function catetree($cateRes){ return $this->sort($cateRes); } public function sort($cateRes,$pid=0,$level=0){ static $arr=array(); foreach ($cateRes as $k => $v) { if($v['pid']==$pid){ $v['level']=$level; $arr[]=$v; $this->sort($cateRes,$v['id'],$level+1); } } return $arr; } // 处理栏目排序 public function cateSort($data,$obj){ foreach ($data as $k => $v) { $obj->update(['id'=>$k,'sort'=>$v]); } } //获取子栏目id public function childrenids($cateid,$obj){ $data=$obj->field('id,pid')->select(); return $this->_childrenids($data,$cateid); } private function _childrenids($data,$cateid){ static $arr=array(); foreach ($data as $k => $v) { if($v['pid']==$cateid){ $arr[]=$v['id']; $this->_childrenids($data,$v['id']); } } return $arr; } //处理批量删除 public function pdel($cateids){ foreach ($cateids as $k => $v) { $childrenidsarr[]=$this->childrenids($v); $childrenidsarr[]=(int)$v; } $_childrenidsarr=array(); foreach ($childrenidsarr as $k => $v) { if(is_array($v)){ foreach ($v as $k1 => $v1) { $_childrenidsarr[]=$v1; } }else{ $_childrenidsarr[]=$v; } } $_childrenidsarr=array_unique($_childrenidsarr); $this::destroy($_childrenidsarr); } }
调用说明:在extend目录下新建一个目录 catetree 目录,再新建文件 Catetree.php
控制器里:
<?php namespace app\admin\controller; use think\Controller; use catetree\Catetree; //引入扩展类 class Cate extends controller { public function lst() { $cate=new Catetree(); $cateObj=db('cate'); $cateRes= $cateObj->order('sort desc')->select(); $cateRes = $cate->catetree($cateRes); $this->assign('cateRes',$cateRes); return view(); } public function add() { $cate=new Catetree(); $cateObj=db('cate'); if(request()->isPost()){ $data=input('post.'); $cateId=$cateObj->field('pid')->find($data['pid']); $add=$cateObj->insert($data); if($add){ $this->success('操作成功!','lst'); }else{ $this->error('操作失败!'); } return; } $cateRes= $cateObj->order('sort desc')->select(); $cateRes = $cate->catetree($cateRes); $this->assign('cateRes',$cateRes); return view(); } //删除(实现删除顶级分类,删除所有子类文章) public function del($id) { $cate=db('cate'); $cateTree = new Catetree(); $sonids=$cateTree->childrenids($id,$cate); $sonids[]=intval($id); $article=db('article'); foreach ($sonids as $k => $v) { $artRes=$article->field('id,thumb')->where(array('cate_id'=>$v))->select(); foreach ($artRes as $k1 => $v1) { $thumbSrc=IMG_UPLAODS.$v1['thumb']; if(file_exists($thumbSrc)){//判断文件是否存在 @unlink($thumbSrc); } $article->delete($v1['id']); } } $del=$cate->delete($sonids); if($del){ $this->success('操作成功!','lst'); }else{ $this->error('操作失败!'); } } }
视图模板:
呈现层级效果:str_repeat(string,repeat) 函数把字符串重复指定的次数。
<td><?php echo str_repeat('-', $cate['level']*8) ?>{$cate.cate_name}</td>
文章评论(0)