php - 展平具有父子关系的数组,以便所有子项都在父级

标签 php arrays json multidimensional-array flatten

早上好,给定以下数据结构(为便于阅读,采用 JSON 格式)

[
{
    "parent": "root",
    "active": "1",
    "label": "Index",
    "route": "/",
    "children": [
        {
            "parent": "/",
            "active": "1",
            "label": "Products",
            "route": "/products",
            "children": [
                {
                    "parent": "/products",
                    "active": "0",
                    "label": "Test",
                    "route": "/test"
                }
            ]
        }
    ]
    },
    {
        "parent": "root",
        "active": "1",
        "label": "404",
        "route": "/404"
    },
    {
        "parent": "root",
        "active": "1",
        "label": "Login",
        "route": "/login"
    }
]

我在从以下结构的函数返回时遇到了很大的麻烦:

[
{
    "parent": "root",
    "active": "1",
    "label": "Index",
    "route": "/"
},
{
    "parent": "/products",
    "active": "0",
    "label": "Test",
    "route": "/test"
},
{
    "parent": "/",
    "active": "1",
    "label": "Products",
    "route": "/products"
},
{
    "parent": "root",
    "active": "1",
    "label": "404",
    "route": "/404"
},
{
    "parent": "root",
    "active": "1",
    "label": "Login",
    "route": "/login"
}
]

本质上,我想遍历所有子项并用嵌套数组中的每个父项和子项填充一个新数组,我尝试了 array_mergeRecursiveIteratorIteratoriterator_to_arrayarray_map,但它总是在递归时出现问题。当 children 只有一层深度但两层或更多层完全崩溃时,我设法做到了。

最佳答案

简单的

function flatten($items, &$r) {
    foreach($items as $item) {
        $c = isset($item->children) ? $item->children : null;
        unset($item->children);
        $r []= $item;
        if($c)
            flatten($c, $r);
    }
}

flatten(json_decode($json), $r);
print_r($r);

这会将结果累积在一个缓冲区中,通过引用传递。这比在每次迭代中构建一个全新的数组要有效得多,后者基本上是 Shlemiel the painter's algorithm 的变体。 .

如果您更喜欢函数式方法,可以使用 generators :

function flatten($items) {
    foreach($items as $item) {
        $c = isset($item->children) ? $item->children : [];
        unset($item->children);
        yield $item;
        foreach(flatten($c) as $child)
            yield $child;
    }
}

foreach(flatten(json_decode($json)) as $item)
    print_r($item);

关于php - 展平具有父子关系的数组,以便所有子项都在父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28393612/

相关文章:

php - 检索查询中的最新日期

Javascript嵌套For循环数组具有隐藏值

java - 错误 : Could not write JSON: Class java. util.ArrayList 不是映射的子类型 - Spring 应用程序中序列化为 JSON

json - WHERE BETWEEN 子句中的 PostgreSQL jsonb 值

PHP:这是一个错误吗:shuffle() 期望参数 1 是数组,给定对象?

php - 在 php 代码中使用 "INSERT INTO"语句不起作用

php - Paypal 响应获取 "Fail"

c - 如何以编程方式获取二维数组中元素的相邻元素?

指向数组的指针的 C++ 指针

java - Jersey:具有 1 个元素的 Json 数组被序列化为对象