php - 将 App.net 对话线程化到树中

标签 php json algorithm tree

我想从平面结构创建一个 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/

相关文章:

php - 在php中下载安全相关问题

php - 如何在 php 中使用 C modf 函数?

php - 带有可选日期参数的 REST 路由

php - 在 Google map 上打印大 map

algorithm - 在具有变化值的两个数组之间进行插值

从1到n计算5个区间点的算法

javascript - 根据 AngularJS 中的两个变量进行升序排序/排序

c# - 将xml树转换为json树

javascript - 如何从 Meteor 中的文件夹中读取所有 JSON 文件?

php - 计算循环内的确切 sleep 时间