商品分類遞歸刪除
商品分類遞迴刪除
#刪除我們之前也做過,但是又有些不同,分類的刪除更為複雜點,我們在刪除頂級欄目的時候應(yīng)該連同頂級欄位下面的分類也一起刪除。
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;空數(shù)組用來儲存id.
foreach 去遍歷數(shù)據(jù),當(dāng)他的pid等於當(dāng)前id的時候說明是頂級,這時候吧id存入到$ res[]這個空數(shù)組中,再用遞歸呼叫。
return array_unique($res);是Eileen回傳這個陣列,array_unique去重。
$childids=implode(',',$childids);把陣列分割成字串就可以使用了。
這是刪除頂級欄位就能發(fā)現(xiàn)刪除的是多個了.