需求:
数据库有某表department表,为了是记录部门的结构,表中包含3个主要字段:id、parentId、name。现在要把这个记录集有规则的树形输出出来。
思路:
无外乎是写处理这个排序的问题。初步想法可以用SQL读出然后后台排序,这么成熟的需求肯定有代码,所以懒的写,但是找了几个都不太满意,那么就打算从前台找一下解决方案。在前台进行排序。于是翻了几页Jquery easyui的文档,发现了可以这么解决:
1、写一个简单的程序,用Json输出全部department记录(输出地址为http://localhost:8080/app/index.php/Department/tree)
2、在前台处理这个记录,进行排序。代码都是现成的。
操作:
第1步:在模版对应的xxxAction页面中写一个函数,主要为了输出tree的json
public function tree()
{
$subproject = M('department');
$list = $subproject->select();
echo JSON_ENCODE($list);
}第2步:把下面代码copy到模版页面的head中: <script type="text/javascript">
function convert(rows){
function exists(rows, parentId){
for(var i=0; i<rows.length; i++){
if (rows[i].id == parentId) return true;
}
return false;
}
var nodes = [];
// get the top level nodes
for(var i=0; i<rows.length; i++){
var row = rows[i];
if (!exists(rows, row.parentId)){
nodes.push({
id:row.id,
text:row.name
});
}
}
var toDo = [];
for(var i=0; i<nodes.length; i++){
toDo.push(nodes[i]);
}
while(toDo.length){
var node = toDo.shift(); // the parent node
// get the children nodes
for(var i=0; i<rows.length; i++){
var row = rows[i];
if (row.parentId == node.id){
var child = {id:row.id,text:row.name};
if (node.children){
node.children.push(child);
} else {
node.children = [child];
}
toDo.push(child);
}
}
}
return nodes;
}
$(function(){
$('#tt').tree({
url: 'http://localhost:8080/app/index.php/Department/tree',
loadFilter: function(rows){
return convert(rows);
}
});
});
</script> 第三步:
模版的body里面加一行代码:
<ul id="tt"></ul> 跑一下试试吧!
参考:http://www.jeasyui.com/tutorial/tree/tree6.php
