PHP
function format_tree(&$result = [], $fid = 0) {
$tree = [];
if (is_array($result)) {
foreach ($result as $v) {
if ($v['fid'] == $fid) {
$children = format_tree($result, $v['id']);
if ($children) {
$v['sub'] = $children;
}
$tree[] = $v;
}
}
}
return $tree;
}
golang
type Leaf struct{
Id int
Pid int
Deep int
Name string
}
type Tree struck{
Leaf
Children []Tree
}
//无限级分类树
func getTree(data []Leaf, pid int, level int) (ret []Tree) {
for _, item := range data {
if item.Pid == pid {
item.Deep = level
tmp := Tree{Leaf : item}
//data=append(data[:i],data[i+1:]...)
tmp.Children = getTree(data, item.Id, level+1)
if len(tmp.Children) == 0 {
tmp.Children = make([]Tree, 0)
}
ret = append(ret, tmp)
}
}
return
}
golang的另外一个版本
import (
"fmt"
)
type Tree struct {
Id int `json:"id,omitempty"`
Pid int `json:"pid,omitempty"`
Name string `json:"name,omitempty"`
Children []Tree `json:"children,omitempty"`
}
func main() {
list := []Tree{
{Id: 1, Name: "a1"},
{Id: 2, Pid: 1, Name: "a2"},
{Id: 3, Pid: 2, Name: "a3"},
{Id: 4, Pid: 3, Name: "a4"},
{Id: 5, Pid: 0, Name: "a5"},
{Id: 6, Pid: 5, Name: "a6"},
}
var tree []Tree
for _, v := range list {
if v.Pid == 0 {
v.Children = ChildrenTree(&list, v.Id) //树型
//v.Children = ChildrenList(&list, v.Id)//列表型
tree = append(tree, v)
}
}
str, _ := JsonEncode(tree)
fmt.Printf("tree:%s\n", str)
}
// 子级:树型
func ChildrenTree(list *[]Tree, pid int) (children []Tree) {
children = make([]Tree, 0)
for i := 0; i < len(*list); i++ {
if (*list)[i].Pid == pid {
(*list)[i].Children = ChildrenTree(list, (*list)[i].Id)
children = append(children, (*list)[i])
}
}
return
}
// 子级:列表型
func ChildrenList(list *[]Tree, pid int) (children []Tree) {
children = make([]Tree, 0)
for i := 0; i < len(*list); i++ {
if (*list)[i].Pid == pid {
children = append(children, (*list)[i])
children = append(children, ChildrenList(list, (*list)[i].Id)...)
}
}
return
}
func JsonEncode(v interface{}) (string, error) {
bytes, err := json.Marshal(v)
if err != nil {
return "", err
}
return string(bytes), nil
}
输出结果:
[
{
"id": 1,
"name": "a1",
"children": [
{
"id": 2,
"pid": 1,
"name": "a2"
},
{
"id": 3,
"pid": 2,
"name": "a3"
},
{
"id": 4,
"pid": 3,
"name": "a4"
}
]
},
{
"id": 5,
"name": "a5",
"children": [
{
"id": 6,
"pid": 5,
"name": "a6"
}
]
}
]