首页 > 学院 > 开发设计 > 正文

TP框架实现获取无限极分类的树

2019-11-11 05:16:09
字体:
来源:转载
供稿:网友
看了很多别人的实现方法,都没看明白,所以自己写一个。
数据库结构如下:
model里面这样子
<?php/** * Created by PhpStorm. * User: 王柏建 * Date: 2016/10/09 * Time: 11:32 */namespace Api/Model;use Think/Model;class TypeModel extends Model{    //通过admin_id获取分类    public static function getTypeByAdminId($admin_id){        return M('type')->where(array("admin_id"=>$admin_id))->select();    }    //通过条件获取一个分类    public static function getTypeByWhere($where){        return M('type')->where($where)->find();    }        //通过条件获取部分分类    public static function getAllTypeByWhere($where){        return M('type')->where($where)->field("clothes_type_id,clothes_type_father_id,clothes_type_name,clothes_type_icon_url")->select();    }}
最后这里是controller里面的写法。
<?phpnamespace Api/Controller;use Api/Model/TypeModel;use Think/Controller;class TreeController extends Controller {    //记录层    public $div = [];    //记录树    public $tree = [];    //返回树    public function returnTree(){        $tree = [];        //获取目前已经有的结构        $this->getChild(0);  //从第一级开始        //dump($this->tree);   //这里是输出数组        $this->AjaxReturn($this->tree,"json");   //输出json    }    //获取某个分类的子分类以及下面的服饰    public function getChild($clothes_type_father_id){        $types = TypeModel::getAllTypeByWhere(array("clothes_type_father_id"=>$clothes_type_father_id));        if(!$types){            array_pop($this->div);            return;        }        if($clothes_type_father_id == 0){            $this->div[] = 0;        }        else{            $this->div[] = TypeModel::getTypeByWhere(array('clothes_type_id'=>$clothes_type_father_id))['clothes_type_id'];        }        //将获取到的东西放到$this->tree里面        $this->putData($this->tree,$this->div,$types);        //循环这一级里面的类,再获取其子类和下面的服饰        foreach($types as $t){            $this->getChild($t['clothes_type_id']);        }    }    //插入数据到特定下标    public function putData(&$array,$down,$data){        $j = [];        $k = 0;        foreach($down as $d){            if($j == null){                $j[$k] = &$array[$d];            }            else{                $j[$k] = &$j[$k++][$d]['son'];            }        }        $count = count($j)-1;        foreach($data as $d){            $j[$count][$d['clothes_type_id']] = $d;        }        unset($j);        unset($k);    }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表