ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 思路 一:获取 `parent_id`,默认为0 二:查询全部菜单, 三:`foreach` 形成带有 `selected` 的新数组 四:用 `Tree` 类形成带有树形结构结构的内容 五:赋值 ## 代码 ``` <?php namespace app\agent\controller; use think\Controller; use think\Db; use tree\Tree; class MenuController extends Controller { /** * 后台菜单添加 */ public function add() { $tree = new Tree(); $parentId = $this->request->param("parent_id", 0, 'intval'); $result = Db::name('AdminMenu')->order(["list_order" => "ASC"])->select(); $array = []; foreach ($result as $r) { $r['selected'] = $r['id'] == $parentId ? 'selected' : ''; $array[] = $r; } $str = "<option value='\$id' \$selected>\$spacer \$name</option>"; $tree->init($array); $selectCategory = $tree->getTree(0, $str); $this->assign("select_category", $selectCategory); return $this->fetch(); } } ``` ## 要点解析 如图所示,这里是关键,形成一个带`selected` 的新数组 ![mark](http://qiniu.newthink.cc/blog/20171019-101316927.png)