在 PHP 中展平 JSON 多深度数组

Flattening a JSON multi depty array in PHP

早上好,给定以下数据结构(在 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"
}
]

基本上我想遍历所有 children 并用嵌套数组中的每个 parent 和 child 填充一个新数组,我试过 array_merge , RecursiveIteratorIterator, itterator_to_array, array_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);

不是很难:

function flatten(array $array) {
    $branch = [];

    foreach ($array as $item) {
        $children = [];
        if (isset($item['children']) && is_array($item['children'])) {
            $children = flatten($item['children']);
            unset($item['children']);
        }
        $branch = array_merge($branch, [$item], $children);
    }

    return $branch;
}