1 回答
TA贡献1946条经验 获得超3个赞
最后,我找到了解决方案:
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"sort"
_ "github.com/mattn/go-sqlite3"
)
type Organization struct {
ID int `json:"organization_id"`
Name string `json:"organization_name"`
Rang int `json:"organization_rang"`
Children []*Organization `json:"children"`
}
func main() {
db, err := sql.Open("sqlite3", "./database")
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.Query("select ORGANIZATION_ID,ORGANIZATION_NAME,ORGANIZATION_RANG,PARENT_ORGANIZATION_ID from ORG")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
orgs := map[int]*Organization{}
for rows.Next() {
organization := &Organization{}
var parentID sql.NullInt64
if err = rows.Scan(&organization.ID, &organization.Name, &organization.Rang, &parentID); err != nil {
log.Fatal(err)
}
if parentID.Valid {
if parentOrg, ok := orgs[int(parentID.Int64)]; ok {
parentOrg.Children = append(parentOrg.Children, organization)
} else {
orgs[int(parentID.Int64)] = &Organization{ID: int(parentID.Int64)}
orgs[int(parentID.Int64)].Children = append(orgs[int(parentID.Int64)].Children, organization)
}
}
if _, ok := orgs[organization.ID]; ok {
orgs[organization.ID].Name = organization.Name
orgs[organization.ID].Rang = organization.Rang
continue
}
orgs[organization.ID] = organization
}
IDs := []int{}
for k := range orgs {
IDs = append(IDs, k)
}
sort.Ints(IDs)
organizations := []Organization{}
for _, ID := range IDs {
if len(orgs[ID].Children) > 0 && orgs[ID].Rang == 1 {
organizations = append(organizations, *orgs[ID])
}
}
content, err := json.MarshalIndent(organizations, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(content))
}
- 1 回答
- 0 关注
- 119 浏览
添加回答
举报