商品分类递归删除
商品分类递归删除
删除我们之前也做过,但是又有些不同,分类的删除更为复杂点,我们在删除顶级栏目的时候应该连同顶级栏目下面的分类也一起删除。
cate控制器
 public function del($id){
        $cata=D('cate');
        $childids=$cata->getchild($id);
        $childids=implode(',',$childids);
        if($cata->delete($childids)){
          $this->success('删除栏目成功!',U('index'));
        }else{
            $this->error('删除栏目失败!');
        }
    }CateModel模型层
 public function getchild($cateid){
        $data=$this->select();
        return $this->getchildids($data,$cateid);
    }
    public function getchildids($data,$cateid){
        static $res=array();
        $res[]=$cateid;
        foreach ($data as $k => $v) {
            if ($v['pid']==$cateid) {
                    $res[]=$v['id'];
                    $this->getchildids($data,$v['id']);
            }
        }
        return array_unique($res);
    }我们来分层次的来讲解
$childids=$cata->getchild($id);
把id传给getchild方法。
public function getchild($cateid){
        $data=$this->select();
        return $this->getchildids($data,$cateid);
    }这里getchild方法接受到传来的id后查询所有的分类。返回数据和id到getchildids方法。
  public function getchildids($data,$cateid){
        static $res=array();
        $res[]=$cateid;
        foreach ($data as $k => $v) {
            if ($v['pid']==$cateid) {
                    $res[]=$v['id'];
                    $this->getchildids($data,$v['id']);
            }
        }
        return array_unique($res);
    }$res=array();定义一个数组。$res[]=$cateid;空数组用来存储id.
foreach 去遍历数据,当他的pid等于当前id的时候说明是顶级,这时候吧id存入到$res[]这个空数组中,再次用递归调用。
return array_unique($res);是Eileen返回这个数组,array_unique去重。
$childids=implode(',',$childids);把数组分割成字符串就可以使用了。
这是删除顶级栏目就能发现删除的是多个了.
			
									
									
									
									
									
									
									
									
									
									
									
									