golang生成樹狀菜單


參考:https://stackoverflow.com/questions/59709917/build-a-tree-structure-from-parent-child-pairs-in-go

 

Firstly, you should never use pointers to slices unless you really have to. It's more typical to assign a return value to the variable, e.g. mySlice = sliceReturningFunction().

I'm not sure what all the requirements here are, but one solution could be:

  1. Build a map of parent-child relations (map[int][]int).
  2. Pass the root-level relation to a function that recursively builds the categories.

Here's an example recursive function. Note that it returns a new slice rather than mutating a pointer.

func buildCategories(ids []int, relations map[int][]int) []Category { categories := make([]Category, len(ids)) for i, id := range ids { c := Category{ID: id} if childIDs, ok := relations[id]; ok { c.Child = buildCategories(childIDs, relations) } categories[i] = c } return categories } 

I added a full example on the Playground. It's not tested, and I'm sure there are better solutions, but it's simple and might give you some ideas at least. If you're going to have thousands of nodes and this is accessed frequently, you're going to need to optimise beyond Go code alone though.

-------------------------------------------------------------------

下面也是一種方法

 

package main

import (
	"encoding/json"
	"fmt"
)

type Category struct {
	ID       int        `json:"id"`
	ParentId int        `json:"parent_id"`
	Name     string     `json:"name"`
	Url      string     `json:"url"`
	Method   string     `json:"method"`
	Child    []Category `json:"child,omitempty"`
}

func main() {
	dataset := [][]int{{1, 0}, {10, 0}, {2, 1}, {3, 1}, {4, 0}, {5, 4}, {6, 4}, {7, 0}, {8, 7}, {9, 2}}
	// dataset := []Category{{1, 0, "aa", "/ad", "GEt", nil}, {10, 0, "aa", "/ad", "GEt", nil}, {2, 1, "aa", "/ad", "GEt", nil}, {3, 1, "aa", "/ad", "GEt", nil},
	// {4, 0, "aa", "/ad", "GEt", nil}, {5, 4, "aa", "/ad", "GEt", nil}, {6, 4, "aa", "/ad", "GEt", nil}, {7, 0, "aa", "/ad", "GEt", nil}, {8, 7, "aa", "/ad", "GEt", nil},
	// {9, 2, "aa", "/ad", "GEt", nil}}
	relations := relationMap(dataset)
	categories := buildCategories(relations[0], relations) // pass root-level IDs

	j, _ := json.Marshal(categories)
	fmt.Println(string(j))
}

func relationMap(dataset [][]int) map[int][]int {
	relations := make(map[int][]int)
	for _, relation := range dataset {
		child, parent := relation[0], relation[1]
		relations[parent] = append(relations[parent], child)
	}
	return relations
}

func buildCategories(ids []int, relations map[int][]int) []Category {
	categories := make([]Category, len(ids))
	for i, id := range ids {
		c := Category{ID: id}
		if childIDs, ok := relations[id]; ok { // build child's children
			c.Child = buildCategories(childIDs, relations)
		}
		categories[i] = c
	}
	return categories
}

  

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM