本篇文章給大家帶來的內容是關於TP5架構下如何用遞迴實現無限分級(程式碼範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。
我用的是tp5架構,由於項目多處用無限分級,所以我在extend裡面直接建立一個catetree包再建立一個類Catetee.php,就可以在控制器裡面直接引用就可以了
<?phpnamespace 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; } //擷取子欄目id public function childrenids($cateid,$obj){ $data=$obj->field('id,pid')->select(); return $this->_childrenids($data,$cateid,TRUE); } private function _childrenids($data,$cateid,$clear=FALSE){ static $arr=array(); if($clear){ $arr=array(); } foreach ($data as $k => $v) { if($v['pid']==$cateid){ $arr[]=$v['id']; $this->_childrenids($data,$v['id']); } } return $arr; } //處理欄目排序 public function cateSort($data,$obj){ foreach ($data as $k => $v) { $obj->update(['id'=>$k,'sort'=>$v]); } } //處理大量刪除 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); }}