栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

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

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/907676.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号