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

看了很多别人的实现方法,都没看明白,所以自己写一个。

数据库结构如下:


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里面的写法。

<?php
namespace 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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值