【发布时间】:2015-12-05 14:59:53
【问题描述】:
我在 MySQL 数据库中有一些表示树结构的数据,我想将其转换为 JSON。我使用递归函数来读取所有数据,但我不知道如何转换为数组。
这里是递归函数:
public function buildTree($parent, $level) {
// retrieve all children of $parent
$results = Department::all()->where('parent_id',$parent);
// display each child
foreach($results as $result)
{
echo $this->buildTree($result['id'], $level+1);
}
}
以下是我最后想要的 JSON 结果:
[
{
"id":1,
"text":"Root node",
"children":[
{
"id":2,
"text":"Child node 1",
"children":[
{
"id":4,
"text":"hello world",
"children":[{"id":5,"text":"hello world2"}]
}
]
},
{
"id":3,
"text":"Child node 2"
}
]
}
]
【问题讨论】:
标签: php json multidimensional-array jstree