Golang 版无限级菜单分类

李鹏1 502 次浏览

无限级菜单分类是我们比较常用的。

package main

type ArticleClass struct {
	Id       int             `json:"id"`
	ParentID int             `json:"parent_id"`
	Name     string          `json:"name"` 
	List     []*ArticleClass `json:"list,omitempty"`
}

func main(){
   var list []*ArticleClass // 假设已经赋值进去,从 数据库取出的数据

   data := buildData(list)
   result := makeTreeCore(0, data)
}


func buildData(list []*ArticleClass) map[int]map[int]*ArticleClass {
	var data map[int]map[int]*ArticleClass = make(map[int]map[int]*ArticleClass)
	for _, v := range list {
		id := v.Id
		fid := v.ParentID
		if _, ok := data[fid]; !ok {
			data[fid] = make(map[int]*ArticleClass)
		}
		data[fid][id] = v
	}
	return data
}

func makeTreeCore(index int, data map[int]map[int]*ArticleClass) []*ArticleClass {
	tmp := make([]*ArticleClass, 0)
	for id, item := range data[index] {
		if data[id] != nil {
			item.List = makeTreeCore(id, data)
		}
		tmp = append(tmp, item)
	}
	return tmp
}


 

 

 


One thought on “ Golang 版无限级菜单分类 ”

  1. 11

    11

发表评论

? razz sad evil ! smile oops grin eek shock ??? cool lol mad twisted roll wink idea arrow neutral cry mrgreen