简单无限级分类

jerry thinkphp 2015年11月19日 收藏
数据层一个方法递归查询分类,返回多维数组。
控制器一个方法拼接html搞定
效果图:
  1. //没有排序哦~~
  2. //数据库是wordpress的结构,如需了解数据结构,请自行百度wordpress数据库


  3. /*-------------------------------------一下是model层文件-----------------------------------*/
  4. //model层方法
  5. public function getCateTree($parentId=0){
  6.     $Model=new Model();
  7.     $sql='select t1.*,t2.* from t_terms t1
  8.               left join t_term_taxonomy t2 on t1.term_id=t2.term_id
  9.               WHERE t2.taxonomy="category" AND t2.parent='.$parentId;
  10.     $parentCates=$Model->query($sql);
  11.     foreach($parentCates as $key=>$value){
  12.         $parentCates[$key]['child']=$this->getCateTree($value['term_id']);
  13.     }
  14.     return $parentCates;
  15. }

  16. /*---------------------------以下是控制器层文件------------------------------*/

  17. //拼接html方法
  18. /**
  19.  * $cates 分类多维数组
  20.  * $index 多维数组层次,默认$index=1即最顶层,之后每次+1
  21.  * return html
  22.  * */
  23. public function cateTreeHtml($cates,$index)
  24. {
  25.     if($index==1){
  26.         $treeHtml='<ul id="categorychecklist" data-wp-lists="list:category" class="categorychecklist form-no-clear">';//最外侧第一级
  27.     }else{
  28.         $treeHtml = '<ul class="children">';
  29.     }
  30.     foreach ($cates as $value) {
  31.         $child='';
  32.         if (count($value['child']) != 0) {
  33.             $child=$this->cateTreeHtml($value['child'],$index+1);//递归
  34.         }
  35.         $treeHtml .= '<li id="category-'.$value['term_id'].'" class="popular-category">
  36.             <label class="selectit">
  37.             <input value="'.$value['term_id'].'" type="checkbox" name="post_category[]" id="in-category-'.$value['term_id'].'">
  38.             '.$value['name'].'
  39.             </label>
  40.             '.$child//子分类
  41.             .'</li>';
  42.     }
  43.     $treeHtml .= '</ul>';
  44.     return $treeHtml;
  45. }
  46. //////////////////////////////////////////////////////////通过model层获取多维分类多维数组调用cateTreeHtml()方法
  47. //控制器层通过递归函数获取html
  48. $catesHtml=$this->cateTreeHtml($cates,$index=1);
  49. $postTags = $termModel->getPostTags($id);