根据从数据表中查询的多条数据得到树状数据。
数据表中根据 id 与 pid进行区分上下级
具体实现如下:
1.分类排列:
// Menu 菜单
type Menu struct {
Id int
Pid int
CateName string
Desc string
CreateTime int
Children []Menu
}
// TreeList 菜单
type TreeList struct {
Id int
Pid int
CateName string
Desc string
CreateTime int
Children []TreeList
}
// GetMenu 获取菜单
func GetMenu(menuList []Menu,pid int)(treeList []TreeList) {
//treeList := []TreeList{}
for _, v := range menuList {
if v.Pid == pid {
child := GetMenu(menuList,v.Id)
node := TreeList {
Id: v.Id,
Pid: v.Pid,
CateName: v.CateName,
Desc: v.Desc,
CreateTime: v.CreateTime,
}
treeList = append(treeList,node)
treeList = append(treeList, child...)
}
}
return treeList
}
根据如上的方法获得的数据结构是:
2.树状层级结构
// Menu 菜单
type Menu struct {
Id int
Pid int
CateName string
Desc string
CreateTime int
Children []Menu
}
// TreeList 菜单
type TreeList struct {
Id int
Pid int
CateName string
Desc string
CreateTime int
Children []TreeList
}
// GetMenu 获取菜单
func GetMenu(menuList []Menu,pid int)(treeList []TreeList) {
for _, v := range menuList {
if v.Pid == pid {
child := GetMenu(menuList,v.Id)
node := TreeList {
Id: v.Id,
Pid: v.Pid,
CateName: v.CateName,
Desc: v.Desc,
CreateTime: v.CreateTime,
}
node.Children = child
treeList = append(treeList, node)
}
}
return treeList
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)