【发布时间】:2016-10-20 14:08:05
【问题描述】:
我正在尝试从数据库中获取深度未知的类别列表。是否可以使用map[int][]interface{} 并且有可能吗?
type Category struct {
ID int
Name string
ParentID int
}
func GetCategories(db *gorm.DB) map[int][]interface{} {
var result = make(map[int][]interface{})
var categories = []Category{}
db.Where("parent_id = ?", 0).Find(&categories)
for len(categories) > 0 {
var ids []int
for _, cat := range categories {
ids = append(ids, cat.ID)
if cat.ParentID == 0 {
result[cat.ID] = append(result[cat.ID], cat)
} else {
// This work only for 2nd level ...
result[cat.ParentID] = append(result[cat.ParentID], cat)
}
}
}
return result
}
最好的输出是 JSON 数组。例如:
[
{id: 1, name: "Car", Parent: 0, Children: []},
{id: 2, name: "Boat", Parent: 0, Children: [
{id: 4, name: "Fast", Parent: 2, Children: []},
{id: 5, name: "Slow", Parent: 2, Children: [
{id: 6, name: "ExtraSlow", Parent: 5, Children: []},
]},
]},
{id: 3, name: "Rocket", Parent: 0, Children: []}
]
【问题讨论】:
-
有可能,但应该避免。您要查找的类型是
map[int]interface{}。 -
你能用 2/3 级别的示例输出更新问题吗?
标签: arrays list dictionary multidimensional-array go