dd

简单无限级分类

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


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

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

//拼接html方法
/**
 * $cates 分类多维数组
 * $index 多维数组层次,默认$index=1即最顶层,之后每次+1
 * return html
 * */
public function cateTreeHtml($cates,$index)
{
    if($index==1){
        $treeHtml='<ul id="categorychecklist" data-wp-lists="list:category" class="categorychecklist form-no-clear">';//最外侧第一级
    }else{
        $treeHtml = '<ul class="children">';
    }
    foreach ($cates as $value) {
        $child='';
        if (count($value['child']) != 0) {
            $child=$this->cateTreeHtml($value['child'],$index+1);//递归
        }
        $treeHtml .= '<li id="category-'.$value['term_id'].'" class="popular-category">
            <label class="selectit">
            <input value="'.$value['term_id'].'" type="checkbox" name="post_category[]" id="in-category-'.$value['term_id'].'">
            '.$value['name'].'
            </label>
            '.$child//子分类
            .'</li>';
    }
    $treeHtml .= '</ul>';
    return $treeHtml;
}
//////////////////////////////////////////////////////////通过model层获取多维分类多维数组调用cateTreeHtml()方法
//控制器层通过递归函数获取html
$catesHtml=$this->cateTreeHtml($cates,$index=1);
$postTags = $termModel->getPostTags($id);
dd