话不多说,直接上代码:
type Resouce struct {
BaseModel
ParentId uint64 //上级Id
Name string
Children []*Resouce//这里必须是指针
}
func BuildTree(resources []Resouce) Resouce {
//定义根树,既id=0的根节点,我用的时候并不存在于数据库
var rootResouce = Resouce{}
//创建一个map,把父级相同的地址归纳起来
DataMap := make(map[uint64][]*Resouce, len(resources))
//寻找对应的父级,添加子节点集合
for key, _ := range resources {
pid := resources[key].ParentId
DataMap[pid] = append(DataMap[pid], &resources[key])
}
for key, _ := range resources {
if resources[key].ParentId == 0 {
rootResouce.Children = append(rootResouce.Children, &resources[key])
}
resources[key].Children = DataMap[resources[key].Id]
}
// 添加完成,既建立树形关系完成
return rootResouce
}
你的评论,是我最好的支持!谢谢