樹形數據處理
阿新 • • 發佈:2018-05-18
sele ubi 技術分享 UC end alt AC erro ndt
數據庫
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>
效果:
樹形數據處理