go 无限极分类实现 返回树状排列数据 或 树状层级数据

go 无限极分类实现 返回树状排列数据 或 树状层级数据,第1张

根据从数据表中查询的多条数据得到树状数据。

数据表中根据 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
}

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/995399.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存