概述
使用PHP將數(shù)據(jù)組裝成樹狀結(jié)構(gòu),相當(dāng)簡(jiǎn)單稼钩,因?yàn)闆](méi)有類型的轉(zhuǎn)化限制等,數(shù)組即一切达罗,而使用GO語(yǔ)言編寫成較為通用的代碼坝撑,相對(duì)要繁瑣一些,本文為包含了PHP及GO相關(guān)代碼
php組織分類樹粮揉,一個(gè)函數(shù)搞定
//本函數(shù)通過(guò)對(duì)地址的充分使用巡李,只用一層循環(huán),便完成了對(duì)所有數(shù)據(jù)的樹狀結(jié)構(gòu)組織扶认。
//id 數(shù)據(jù)主鍵
//parent_id 父級(jí)數(shù)據(jù)主鍵
public static function makeTree($records)
{
$tree = [];
$data = [];
foreach ($records as $item) {
$item['children'] = [];
$data[$item['id']] = $item;
}
foreach ($data as $item) {
if ($item['parent_id'] != 0 && isset($data[$item['parent_id']])) {
$data[$item['parent_id']]['children'][] = &$data[$item['id']];
} else {
$tree[] = &$data[$item['id']];
}
}
return $tree;
}
使用go完成相應(yīng)功能侨拦,要使用到接口
- 接口定義,組織樹狀結(jié)構(gòu)的方法辐宾,需要使用到此接口內(nèi)的相關(guān)方法
type NodeWithChildren interface {
GetID() int
GetParentID() int
GetChildren() []NodeWithChildren
SetChildren(children []NodeWithChildren)
}
2.方法
func BuildTree(nodes []NodeWithChildren) []NodeWithChildren {
nodeMap := make(map[int]NodeWithChildren)
// 將所有節(jié)點(diǎn)放入 map 中狱从,以 ID 作為 key
for _, node := range nodes {
nodeMap[node.GetID()] = node
}
// 遍歷節(jié)點(diǎn),根據(jù) ParentID 將子節(jié)點(diǎn)連接到對(duì)應(yīng)的父節(jié)點(diǎn)上
var rootNodes []NodeWithChildren
for _, node := range nodes {
parentID := node.GetParentID()
if parentID == 0 {
rootNodes = append(rootNodes, node)
} else {
parent, ok := nodeMap[parentID]
if ok {
children := parent.GetChildren()
children = append(children, node.(NodeWithChildren))
parent.SetChildren(children)
}
}
}
return rootNodes
}
3.使用此方法的結(jié)構(gòu)體叠纹,必須實(shí)現(xiàn)接口所有方法矫夯,例
//以下為要組織成樹狀結(jié)構(gòu)的結(jié)構(gòu)體
type ArticleCategory struct {
ID int `gorm:"column:id;primaryKey;autoIncrement:true" json:"id"`
Pid int `gorm:"column:pid;not null" json:"pid"`
Name string `gorm:"column:name;not null" json:"name"`
Intro string `gorm:"column:intro" json:"intro"`
Sort int32 `gorm:"column:sort;not null" json:"sort"`
Cover string `gorm:"column:cover" json:"cover"`
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at" json:"deleted_at"`
Children []NodeWithChildren `gorm:"-"`//此處表示不從數(shù)據(jù)庫(kù)中查找此字段
}
func (c *ArticleCategory ) GetID() int {
return c.ID
}
func (c *ArticleCategory ) GetParentID() int {
return c.Pid
}
func (c *ArticleCategory ) GetChildren() []NodeWithChildren {
return c.Children
}
func (c *ArticleCategory ) SetChildren(children []NodeWithChildren) {
c.Children = children
}
func (c *ArticleCategory ) MakeTree(records []ArticleCategory ) []NodeWithChildren {
var convertedNodes []NodeWithChildren
for _, category := range records {//這一步很關(guān)鍵,此處將數(shù)據(jù)轉(zhuǎn)換為NodeWithChildren
cat := category
convertedNodes = append(convertedNodes, &cat)
}
return BuildTree(convertedNodes)
}
4.打印樹結(jié)構(gòu)
func PrintTree(trees interface{}) {
b, _ := json.MarshalIndent(trees, "", " ")
fmt.Println(string(b))
}
4.使用gorm獲取數(shù)據(jù)并進(jìn)行測(cè)試
var DB *gorm.DB
func initDb() {
var err error
DB, err = gorm.Open(mysql.Open("root:123456@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local&timeout=1000ms"), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true, //英語(yǔ)單數(shù)形式
},
})
//gorm.Open(cfg.Driver, cfg.Source)
DB = DB.Debug() //調(diào)式模式
if err != nil {
panic("數(shù)據(jù)庫(kù)連接失敗:" + err.Error())
}
}
func main() {
initDb()
var mts []ArticleCategory
err := DB.Model(&ArticleCategory {}).Find(&mts).Error
if err != nil {
panic(err)
}
article := dao.ArticleCategory {}
tree := article .MakeTree(mts)
PrintTree(tree)//打印樹
}
以上吊洼,記錄php及go生成樹狀結(jié)構(gòu)的相關(guān)思路