-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
63 lines (56 loc) · 1.18 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
import (
"fmt"
"encoding/json"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
//使用map来实现简单golang无限分类
type Cat struct {
Id int
Fid int
Name string
Children []*Cat `orm:"-"`
}
func main() {
var o = orm.NewOrm()
var list []*Cat
o.QueryTable("cat").All(&list)
tree := tree(list)
fmt.Println(tree)
}
func init() {
orm.RegisterDataBase("default", "mysql", "root:leozim?@/learn?charset=utf8")
orm.RegisterModel(new(Cat))
}
func tree(list []*Cat) string {
data := buildData(list)
result := makeTreeCore(0, data)
body, err := json.Marshal(result)
if err != nil {
fmt.Println(err)
}
return string(body)
}
func buildData(list []*Cat) map[int]map[int]*Cat {
var data map[int]map[int]*Cat = make(map[int]map[int]*Cat)
for _, v := range list {
id := v.Id
fid := v.Fid
if _, ok := data[fid]; !ok {
data[fid] = make(map[int]*Cat)
}
data[fid][id] = v
}
return data
}
func makeTreeCore(index int, data map[int]map[int]*Cat) []*Cat {
tmp := make([]*Cat, 0)
for id, item := range data[index] {
if data[id] != nil {
item.Children = makeTreeCore(id, data)
}
tmp = append(tmp, item)
}
return tmp
}