数据树形显示
public List<Map<String, Object>> getMenus() throws Exception {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
//查出表数据
List<Map<String, Object>> areas = wmdao.getMenus();
// 找出第一级
for (Map<String, Object> area : areas) {
System.out.println("**************");
System.out.println(area);
//取出name
String name = (String) area.get("name");
//将name添加到area中
area.put("text", name);
System.out.println("**put************");
System.out.println(area);
//
Integer pid = (Integer) area.get("pid");
//判断如果为-1就为根节点
if (pid == -1) {
//将第一级加入list
list.add(area);
//第一级的进入getChildren方法
getChildren(area, areas);
}
}
System.out.println("最终返回的list结构");
for (Map<String, Object> li : list) {
System.out.println(li);
}
return list;
}
//传递的参数parent(pid为-1的数据)
private void getChildren(Map<String, Object> parent, List<Map<String, Object>> areas) {
//取出id
Integer id = (Integer) parent.get("id");
for (Map<String, Object> area : areas) {
//取出上级id
Integer pid = (Integer) area.get("pid");
if (pid == null)
continue;
//
if (id.intValue() == pid.intValue()) {
List<Map<String, Object>> children = (List<Map<String, Object>>) parent.get("children");
if (children == null) {
children = new ArrayList<Map<String, Object>>();
parent.put("children", children);
}
children.add(area);
getChildren(area, areas);
}
}
}
返回结果
最终返回的list结构
{id=43, name=微商城, type=view, link=http://wx.miaolives.com, key=null, time=2018-03-12 15:36, pid=-1, text=微商城}
{id=48, name=我的, type=view, link=null, key=null, time=2018-03-12 15:39, pid=-1, text=我的, children=[{id=51, name=我的账户, type=view, link=http://wx.miaolives.com/me.html, key=null, time=2018-03-12 15:40, pid=48, children=[{id=49, name=领取会员卡, type=view, link=http://wx.miaolives.com/me.html, key=null, time=2018-03-12 15:39, pid=51, text=领取会员卡}], text=我的账户}]}
前端使用树形表格显示数据
$("#wx_menus").treegrid({})
总结:
步骤:
- 前端页面使用treegrid(树形菜单)显示
- 数据准备
- 数据库查出数据结果(类型:List<Map<String, Object>>)
- 使用循环先判断pid(级别),取出pid为-1(顶级)的值
- 将顶级数据存入新创建的List<Map<String, Object>>
- 将顶级数据与结果集传入另一个方法,查询第二级数据
- 第二级判断:
- 将顶级的id与其他数据的pid进行比较,满足条件的数据,存放到顶级数据的children中
if (id.intValue() == pid.intValue()) {
List<Map<String, Object>> children = (List<Map<String, Object>>) parent.get("children");
if (children == null) {
children = new ArrayList<Map<String, Object>>();
parent.put("children", children);
}
children.add(area);
//递归
getChildren(area, areas);