我想从平面结构创建一个 JSON 树——在本例中是一个 App.net 线程。
我想要这样的 JSON
"id": "12345",
"name": "Ringo",
"data":
{
"avatar": "",
"text": "We All Live",
},
"children": [{
"id": "34567",
"name": "John",
"data":
{
"avatar": "",
"text": "In a pink submarine?",
},
"children": [{
"id": "35555",
"name": "George",
"data":
{
"avatar": "",
"text": "Don't be daft",
},
"children": []
}]
},{
"id": "98765",
"name": "Paul",
"data":
{
"avatar": "",
"text": "In a yellow submarine?",
},
"children": []
}]
因此,每个帖子可以有多个 child 。每个 child 都可以有 child 。
从 App.net 返回的 JSON 未线程化。
{
"id": "98765",
"parent": "12345"
"details": {
...}
},
{
"id": "34567",
"parent": "12345"
"details": {
...}
},
我使用 json_decode() 将 JSON 响应获取到一个数组中。我可以使用 foreach 进行迭代。
如何将每个帖子放入多维数组的正确部分?
Parent
|_
|-child
|-child
| |-child
|-child
等等
最佳答案
我会使用引用,即经常被遗忘的 PHP 硬链接(hard link)。像这样:
我假设您有一个从 App.net API 调用中返回的 $posts
数组。
(未经测试,可能无法编译/运行/可能有错误/可能是更有效的方法)
// first throw everything into an associative array for easy access
$references = array();
foreach ($posts as $post) {
$id = $post['id'];
$post['children'] = array();
$references[$id] = $post;
}
// now create the tree
$tree = array();
foreach ($references as &$post) {
$id = $post['id'];
$parentId = $post['parent'];
// if it's a top level object, add it to the tree
if (!$parentId) {
$tree[] =& $references[$id];
}
// else add it to the parent
else {
$references[$parentId]['children'][] =& $post;
}
// avoid bad things by clearing the reference
unset($post);
}
// encode it
print json_encode($tree);
关于php - 将 App.net 对话线程化到树中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12219340/