数据库
Controller递归处理
public function getDeptTree() { $deptdata = Db::table('dept')->field('dept_name,dept_no,p_id')->select(); $showdata = $this->getTree($deptdata, $p_id = 0, $depth = 0); $data = json($showdata); return $data; } // //部门树形数据组装 public function getTree($treedata, $p_id, $depth) { $retnArr = array(); if (!empty($treedata)) { foreach ($treedata as $key => $info) { if ($info['p_id'] == $p_id) { $info['depth'] = $depth; $temp_info = $info; foreach ($treedata as $subinfo) { if ($subinfo['p_id'] == $info['dept_no']) { $temp_info['sub'] = $this->getDeptTree($treedata, $info['dept_no'], $depth + 1); } } $retnArr[] = $temp_info; } } } return $retnArr; }
递归处理后返回的json类型数据
view:
<div>
<ul id="tree" class="filetree"></ul>
</div>
<script> //页面加载 $(function(){ //递归遍历方法 function getTrees(obj,data){ for(var i=0;i<data.length;i++){ var ul = $("<ul></ul>"); var childli= $('<li><span class="folder">'+data[i]['dept_name']+'</span></li>'); childli.appendTo(obj).append(ul); if(data[i]['sub']){ getTrees(ul,data[i]['sub']); } } } //页面加载时发送异步请求返回json类型树形数据,进行递归处理 $.ajax({ url: "{:url('deptc/getDeptTree')}", type: 'post', dataType: 'json', error: function(data) { console.log(data); }, success: function(data) { // var li=$('<li><span class="folder">'+data[0]['dept_name']+'</span></li>'); // $(li).appendTo($('#tree')); getTrees($("#tree"),data); $("#tree").treeview(); } }); }); </script>
效果: