最近工作中遇到了这样的一个场景,需要处理一个无限极分类的问题,对于数据结构的定义首先想到了,map,map[int]map[int]struct。通过两层map的定义归类parent_id和id的关系,然后有个递归进行数据的绑定处理。想想就开心,map确实好用,虽然不是并发安全,但是在查询速度和检查值存在方面确实有优势,然后就开心的写了起来,但是想起来map的输出是无序的。然后就想办法去处理数据的输出。刚开始,思路错了,老想着在数据的绑定层,就处理好,数据的顺序,于是就想着用切片map,map切片。。。来处理,越想越复杂,数据结构越想越复杂。忽然想到,为什么不把map的key排序,然后就行输出呢,问题一下子解决了。
// buildData 数据的资源组装 func (myL *BusinessRelationLogic) buildData(list []models.BusinessRelationOther) map[int]map[int]models.BusinessRelationOther { var data map[int]map[int]models.BusinessRelationOther = make(map[int]map[int]models.BusinessRelationOther) for _, v := range list { id := v.Id fid := v.ParentId if _, ok := data[fid]; !ok { data[fid] = make(map[int]models.BusinessRelationOther) } data[fid][int(id)] = v } return data } // makeTreeCore 图形化 func (myL *BusinessRelationLogic) makeTreeCore(index int, data map[int]map[int]models.BusinessRelationOther) []models.BusinessRelationOther { tmp := make([]models.BusinessRelationOther, 0) var keys []int for k, _ := range data[index] { keys = append(keys, k) } sort.Ints(keys) //排序切片key res := models.BusinessRelationOther{} for _, id := range keys { utils.ChangeStruct2OtherStruct(data[index][id], &res) if data[id] != nil { res.List = myL.makeTreeCore(id, data) } tmp = append(tmp, res) } return tmp }
问题解决
package main import ( "fmt" "sort" ) func main() { a:= map[string]string{"1":"a","2":"b","3":"c","4":"d"} var keys [] string for k := range a{ keys = append(keys, k) } sort.Strings(keys)//排序切片key fmt.Println(keys,len(keys)) for _,val := range keys{ //循环key取值 fmt.Println(a[val]) } }