将App.net对话线程转换为树形结构

3

我希望从扁平结构中创建一个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": []
    }]

因此,每篇帖子都可以有多个子级。每个子级都可以有子级。

从 App.net 返回的 JSON 不是 线程化的。

{
    "id": "98765",
    "parent": "12345"
    "details": {
    ...}
},
{
    "id": "34567",
    "parent": "12345"
    "details": {
    ...}
},

我已经使用json_decode()将JSON响应转换成数组。我可以使用foreach进行迭代。
如何将每个帖子放入多维数组的正确部分?
Parent
|_
  |-child
  |-child
  |  |-child
  |-child

etc

3个回答

4
我会使用 PHP 中经常被忽略的硬链接——引用。像这样:
假设您已经从 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);

0

我写了一个类和示例脚本来完成我认为你想要的。

它将扁平结构转换为分层结构,并考虑孤立更新(没有可用父级更新的更新)。

Update.php

<?php

/**
 * An App.net update.
 */
class Update extends ArrayObject
{
    /**
     * The update's children.
     *
     * @var array
     */
    private $children = array();

    /**
     * The parent update.
     *
     * @var Update
     */
    private $parent;

    /**
     * Adds a child to this update.
     *
     * @param Update The child update.
     */
    public function addChild(self $child)
    {
        $child->setParent($this);

        $this->children[] = $child;
    }

    /**
     * Sets the parent update.
     *
     * @param Update The parent update.
     */
    public function setParent(self $parent = null)
    {
        $this->parent = $parent;
    }

    /**
     * Converts the update and its children to JSON.
     *
     * @param boolean $encode Automatically encode?
     *
     * @return string The JSON-encoded update.
     */
    public function toJson($encode = true)
    {
        $data = $this->getArrayCopy();

        if ($this->children) {
            $data['children'] = array();

            foreach ($this->children as $child) {
                $data['children'][] = $child->toJSON(false);
            }
        }

        if ($encode) {
            return json_encode($data);
        }

        return $data;
    }
}

build.php

<?php

require 'Update.php';

$updates = <<<UPDATES
[
    {
        "id": "12345",
        "name": "Ringo",
        "data": {
            "avatar": "",
            "text": "We All Live"
        }
    },
    {
        "id": "34567",
        "parent": "12345",
        "name": "John",
        "data": {
            "avatar": "",
            "text": "In a pink submarine?"
        }
    },
    {
        "id": "98765",
        "parent": "12345",
        "name": "Paul",
        "data": {
            "avatar": "",
            "text": "In a yellow submarine?"
        }
    }
]

UPDATES;

$original = json_decode($updates, true);
$parents = array();
$children = array();

foreach ($original as $update) {
    if (empty($update['parent'])) {
        $parents[$update['id']] = $parent = new Update($update); 

        if (isset($children[$update['id']])) {
            foreach ($children[$update['id']] as $child) {
                $parent->addChild($child);
            }

            unset($children[$update['id']]);
        }
    } else {
        $child = new Update($update);

        if (isset($parents[$update['parent']])) {
            $parents[$update['parent']]->addChild($child);
        } else {
            if (false === isset($children[$update['parent']])) {
                $children[$update['parent']] = array();
            }

            $children[$update['parent']][] = $child;
        }
    }
}

// Anything in children at this point are orphans

echo "Parents:\n";

foreach ($parents as $parent) {
    echo $parent->toJson();
}

echo "\n\nOrphans:\n";

foreach ($children as $parent => $orphans) {
    foreach ($orphans as $orphan) {
        echo $orphan->toJson();
    }
}

0

这里只是简单地勾勒出一个答案:假设您可以将所有条目保存在RAM中,否则您将不得不做一些排序假设,并在完成一个完整的单元时清除数组。

创建一个由id索引的posts数组,其中包含详细信息和子数组的结构。 然后遍历您的输入数组,并针对每个元素:

  • 如果尚未创建,请创建posts[id]
  • 填写post[id]的详细信息
  • 如果有父项,请查找(如果需要创建-不知道排序方式)posts[parent_id]并将此结构添加到其子项中。

最后,您可以遍历所有帖子,没有父项的帖子是根,其子项已正确填充。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接