thinkPHP5无限级分类demo

  • A+
所属分类:PHP

mysql表主要字段:

id

catename 分类名称

pid 父级id

tp5代码:

<?php
namespace app\index\model;
use think\Model;
use think\Db;

class Menu extends Model{
    public function getmenu(){
        // 查询数据
        $data = Db::name('menu')
            ->field('id,catename,pid')
            // ->where("pid = $pid")
            ->select();

        $arr=$this::_get_child($data); //得到菜单数组
        $json=json_encode($arr);
        return $json; //返回json格式
    }


    //分类级别
    static protected function _cate_level($data, $pid=0, $level=0){
        $array = array();
        foreach ($data as $k => $v){
            if ($v['pid'] == $pid){
                $v['level'] = $level;
                $array[] = $v;
                unset($data[$k]);
                $array = array_merge($array, self::_cate_level($data, $v['id'],$level+1)); //递归
            }
        }
        return $array;
    }



    //菜单
    static protected function _get_child($data, $pid=0){
        $array = array();
        foreach ($data as $k => $v){
            if ($v['pid'] == $pid){
                $v['child'] = self::_get_child($data, $v['id']); //递归
                $array[] = $v;
            }
        }
        return $array;
    }
    // 或者:
    static protected function _get_child($data, $pid=0){
        $array = [];
        foreach ($array as $v) {
            if($pid == $v['pid']){
                $v['child'] = $this->_get_child($data,$v['id']);
                $array[] = $v;
            }
        }
        return $array;
    }
}

 

 

weinxin
我的微信公众号
我的微信公众号扫一扫

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: