tp3.2.3无限级分类

时间:2022-09-25 21:28:25

一、数据库(存储分类信息的表)

tp3.2.3无限级分类

二、代码实现

1、添加分类

public function add(){
$cate=D('category');
if(IS_POST){
$data['cate_name']=I('cate_name');
$data['cate_ename']=I('cate_ename');
$data['cate_keywords']=I('cate_keywords');
$data['cate_desc']=I('cate_desc');
$data['cate_type']=I('cate_type');
$data['parentid']=I('parentid');
$data['cate_content']=I('cate_content');
$data['cate_pic']='';
if($_FILES['cate_pic']['tmp_name']!=''){
$upload=new \Think\Upload();
$upload->maxSize=3145728 ;
$upload->exts=array('jpg', 'gif', 'png', 'jpeg');
$upload->savePath='./Public/Uploads/';
$upload->rootPath='./';
$info=$upload->uploadOne($_FILES['cate_pic']);
if(!$info){
$this->error($upload->getError());
}else{
$data['cate_pic']=$info['savepath'].$info['savename'];
}
}
if($cate->create($data)){
if($cate->add()){
$this->success('添加成功!',U('lst'));
}else{
$this->error('添加失败!',U('lst'));
}
}else{
$this->error($cate->getError());
}
return;
}
$cateres=$cate->catetree();
$this->assign('cateres',$cateres);
$this->display();
}

注:添加成功失败提醒用的是tp自带的,界面特丑,建议使用javascript。

2、显示分类

控制器:

public function lst(){
$cate=D('category');
$category=$cate->catetree();
$this->assign('cates',$category);
$this->display();
}

模型:

//分类树
public function catetree(){
$data=$this->select();
return $this->resort($data);
}
public function resort($data,$parentid=0,$level=0){
static $ret=array();
foreach ($data as $k=>$v){
if($v['parentid']==$parentid){
$v['level']=$level;
$ret[]=$v;
$this->resort($data,$v['cate_id'],$level+1);
}
}
return $ret;
}

3、删除分类

删除分类有两种处理方式:一种是其下一级分类改为*分类;另一种是将其所有子级分类删除。下面是第二种处理方法的代码实现:
控制器:

public function del($cate_id){
$cate=D('category');
if($cate->delete($cate_id)){
$this->success('删除成功!',U('lst'));
}else{
$this->error('删除失败!');
}
}

模型:

public function childrenid($cate_id){
$data=$this->select();
return $this->getChildrenid($data,$cate_id);
}
public function getChildrenid($data,$parentid){
static $ret=array();
foreach ($data as $k=>$v){
if($v['parentid']==$parentid){
$ret[]=$v['cate_id'];
$this->getChildrenid($data,$v['cate_id']);
}
}return $ret;
}
public function _before_delete($options){
if(is_array($options['where']['cate_id'])){
$arr=explode(',',$options['where']['cate_id'][1]);
$soncates=array();
foreach($arr as $k=>$v){
$soncates2=$this->childrenid($v);
$soncates=array_merge($soncates,$soncates2);
}
$soncates=array_unique($soncates);
$soncates=implode(',',$soncates);
if($soncates){
$this->execute("delete from cy_category where cate_id in ($soncates)");
}
}else{
$childrenids=$this->childrenid($options['where']['cate_id']);
$childrenids=implode(',',$childrenids);
if($childrenids){
$this->execute("delete from cy_category where cate_id in ($childrenids)");
}
}
}