ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 控制器 ~~~ public function index(){ $data = db('menu')->order('listorder')->select(); $result = Menu::tree($data); p($result);exit; return view(); } ~~~ ## 模型 ~~~ <?php namespace app\admin\model; use think\Model; class Menu extends Model{ // 无限级分类,仅供教学使用 public static $treeListEasy = array(); public static function treeEasy($data, $parentid = 0){ foreach ($data as $key => $value) { if ($value['parentid'] == $parentid) { self::$treeListEasy[$value['id']][] = $value; self::treeEasy($data,$value['id']); } } return self::$treeListEasy; } // 无限级分类,仅供教学使用 public static $treeListTest = array(); public static $pid = 0; public static $sid = 0; public static function treeTest($data, $parentid = 0, $level = 1){ foreach ($data as $key => $value) { if ($value['parentid'] == $parentid) { if ($level == 1) { self::$pid = $value['id']; self::$treeListTest[self::$pid] = $value; }else if ($level == 2) { self::$sid = $value['id']; self::$treeListTest[self::$pid]['son'][self::$sid] = $value; }elseif ($level == 3) { self::$treeListTest[self::$pid]['son'][self::$sid]['son'][] = $value; } if ($value['child']) { self::treeTest($data, $value['id'], $level+1); } } } return self::$treeListTest; } // 无限级分类,开发使用 public static function tree($data){ $tree = []; // 第1步,将所有菜单项的ID作为数组下标 foreach ($data as $value) { $tree[$value['id']] = $value; } // 第2步,利用引用的方式,将每个子菜单项添加到父类son的数组中,只需遍历一次 foreach ($tree as $key => $value) { if ($value['parentid'] != 0) { $tree[$value['parentid']]['son'][] = &$tree[$key]; } } // 第3步,清除重复数据 foreach ($tree as $key => $value) { if ($value['parentid'] != 0) { unset($tree[$key]); } } return $tree; } // 无限级分类,开发使用(优化@2018.6.7) public static function tree($data){ $tree = []; //第1步,将所有菜单项的ID作为数组下标 foreach ($data as $value) { $tree[$value['id']] = $value; } //利用引用的方式,将每个子菜单项添加到父类son的数组中,只需遍历一次 foreach ($tree as $key => $value) $tree[$value['parentid']]['son'][] = &$tree[$key]; $tree = isset($tree[0]['son']) ? $tree[0]['son'] :array(); //原第3步,清除重复数据,已经不需要使用 // foreach ($tree as $key => $value) { // if($value['parentid'] !=0 ){ // unset($tree[$key]); // } // } return $tree; } } ~~~