ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
laytree目前的功能有限,但是样式还是挺好看的,能完成基本的树形展示以及点击的回调操作。 在 application\\index\\controller\\Layer.php 中新建 ~~~ // laytree public function layTree() { if(request()->isAjax()){ $data = [ [ 'id' => 1, 'name' => '江苏省', 'pid' => 0], [ 'id' => 2, 'name' => '徐州市', 'pid' => 1], [ 'id' => 3, 'name' => '睢宁县', 'pid' => 2], [ 'id' => 4, 'name' => '双沟镇', 'pid' => 3], [ 'id' => 5, 'name' => '王集镇', 'pid' => 3], [ 'id' => 6, 'name' => '铜山区', 'pid' => 2], [ 'id' => 7, 'name' => '张集镇', 'pid' => 6], [ 'id' => 8, 'name' => '大黄山镇', 'pid' => 6], [ 'id' => 9, 'name' => '南京市', 'pid' => 1], [ 'id' => 10, 'name' => '江宁区', 'pid' => 9], [ 'id' => 11, 'name' => '鼓楼区', 'pid' => 9], [ 'id' => 12, 'name' => '浙江省', 'pid' => 0], [ 'id' => 13, 'name' => '杭州市', 'pid' => 12], [ 'id' => 14, 'name' => '西湖区', 'pid' => 13] ]; $res = []; $tree = []; // 整理数组 foreach( $data as $key=>$vo ){ $res[$vo['id']] = $vo; $res[$vo['id']]['children'] = []; } unset( $data ); // 查询子孙 foreach( $res as $key=>$vo ){ if( $vo['pid'] != 0 ){ $res[$vo['pid']]['children'][] = &$res[$key]; } } // 去除杂质 foreach( $res as $key=>$vo ){ if( $vo['pid'] == 0 ){ $tree[] = $vo; } } unset( $res ); return json(['code' => 1, 'data' => $tree, 'msg' => 'ok']); } return $this->fetch(); } ~~~ 他需要的数据格式,你可以到官网去查看。这里我整理出的是我总结到的最快的构建出子孙数的方法,无需递归。 新建 application\\index\\view\\layer\\laytree.html ~~~ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title>树模块 - layui</title> <link href="/static/layui/css/layui.css" rel="stylesheet"> <style> body{padding: 50px 100px;} </style> </head> <body> <ul id="demo"></ul> <script src="/static/js/jquery.min.js?v=2.1.4"></script> <script src="/static/layui/layui.js"></script> <script> $(function(){ layui.use('tree', function(){ $.getJSON("{:url('layer/laytree')}", function(res){ var tree = layui.tree({ elem: '#demo' //指定元素 //,check: 'checkbox' //勾选风格 ,skin: 'as' //设定皮肤 //,target: '_blank' //是否新选项卡打开(比如节点返回href才有效) ,drag: true ,click: function(item){ //点击节点回调 console.log(item) } ,nodes: res.data }); }); }); }); </script> </body> </html> ~~~ 访问[http://www.phper.com/index/layer/laytree](http://www.phper.com/index/layer/laytree)就会看到如下的树形菜单 ![](https://box.kancloud.cn/25967da68c8190a9306cde5d6e98ca39_360x392.png)