Recursive deletion of product categories
Deletion We have done it before, but it is a little different. Deletion of categories is more complicated. , when we delete the top-level column, we should also delete the categories below the top-level column.
cate controller
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 model layer
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); }
Let’s explain it hierarchically
$childids=$cata->getchild($id);
Pass the id to the getchild method.
public function getchild($cateid){ $data=$this->select(); return $this->getchildids($data,$cateid); }
The getchild method here queries all categories after receiving the passed id. Return data and id to getchildids method.
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();Define an array. $res[]=$cateid; The empty array is used to store id.
foreach traverses the data. When its pid is equal to the current id, it means it is the top level. At this time, the id is stored in $ In the empty array of res[], use recursion again.
return array_unique($res); Eileen returns this array, array_unique removes duplicates.
$childids=implode(',',$childids); Split the array into strings and you can use it.
This is when you delete the top-level column and you will find that you have deleted multiple ones.
Next Section