package main
import (
"encoding/json"
"fmt"
)
type Good struct {
Id int `json:"id"`
Name string `json:"name"`
Parent int `json:"parent"`
Child []Good `json:"child"`
}
func main() {
iphone_v1 := Good{
Id: 2,
Name: "iphone 14 pro",
Parent: 1,
}
iphone_v2 := Good{
Id: 3,
Name: "iphone 14 pro max",
Parent: 1,
}
iphone_v3 := Good{
Id: 4,
Name: "iphone 14 pro max 256",
Parent: 3,
}
iphone_v4 := Good{
Id: 5,
Name: "iphone 14 pro max 128",
Parent: 3,
}
iphone_v5 := Good{
Id: 6,
Name: "iphone 14 pro max 128 black",
Parent: 5,
}
iphone := Good{
Id: 1,
Name: "iphone 14",
Parent: 0,
}
GoodList := []Good{iphone, iphone_v1, iphone_v2, iphone_v3, iphone_v4, iphone_v5}
result := Exec(0, GoodList)
//echo json
data, _ := json.Marshal(result)
fmt.Println(string(data))
}
func Exec(goodsType int, goods []Good) []Good {
child := make([]Good, 0)
for _, item := range goods {
if goodsType == item.Parent {
node := Exec(item.Id, goods)
item.Child = append(item.Child, node...)
child = append(child, item)
}
}
return child
}
输出结果
[
{
"id": 1,
"name": "iphone 14",
"type": 0,
"child": [
{
"id": 2,
"name": "iphone 14 pro",
"type": 1,
"child": null
},
{
"id": 3,
"name": "iphone 14 pro max",
"type": 1,
"child": [
{
"id": 4,
"name": "iphone 14 pro max 256",
"type": 3,
"child": null
},
{
"id": 5,
"name": "iphone 14 pro max 128",
"type": 3,
"child": [
{
"id": 6,
"name": "iphone 14 pro max 128 black",
"type": 5,
"child": null
}
]
}
]
}
]
}
]