go语言beego框架中实现无极限查找子孙树函数
我个人项目要实现评论显示功能,这里就用到查找子信息评论
所以搞个demo实现以下,记录之
流程:
进入文章详情页,查找出该文章的所有评论,然后通过我写的查找子孙评论信息,显示出来
环境介绍:
windos
编辑器:LiteIDE
开始开发:
定义结构体
type comm struct {
Comment_id int
Fcomment_id int
Art_id int
user_id int
Username string
face string
comment string
pubtime string
Children []comm
}
type Son struct {
Comment_id int
Fcomment_id int
Art_id int
user_id int
Username string
face string
comment string
pubtime string
Children []Son
}
实现函数
//无极限获取子孙树
func SonsTree(comm []comm, pid int) []Son {
//fmt.Println(comm)
s := []Son{}
for _, v := range comm {
if v.Fcomment_id == pid {
child := SonsTree(comm, v.Comment_id)
node := Son{
Comment_id: v.Comment_id,
Fcomment_id: v.Fcomment_id,
Art_id: v.Art_id,
Username: v.Username,
}
node.Children = child
s = append(s, node)
}
}
return s
}
调用:
arrs := []comm{
{Comment_id: 1, Fcomment_id: 0, Art_id: 11, user_id: 11, Username: "11", face: "11", comment: "11", pubtime: "11"},
{Comment_id: 2, Fcomment_id: 0, Art_id: 22, user_id: 22, Username: "22", face: "22", comment: "22", pubtime: "22"},
{Comment_id: 3, Fcomment_id: 2, Art_id: 33, user_id: 33, Username: "我是2的子级", face: "33", comment: "33", pubtime: "33"},
}
list := SonsTree(arrs, 0)
fmt.Println(list)
c.Data["json"] = list
c.ServeJSON()
c.StopRun()
看看效果:
完
相关文章