在PHP中展平JSON多深度数组 [英] Flattening a JSON multi depty array in PHP

查看:104
本文介绍了在PHP中展平JSON多深度数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,给出以下数据结构(为了便于阅读,使用JSON)

Good morning, given the below data structure (in JSON for ease of reading)

[
{
    "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"
    }
]

我很难从函数返回以下结构:

I am having major trouble returning from a function the following structure:

[
{
    "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_merge,RecursiveIteratorIterator,itterator_to_array,array_map,但在递归中始终不会出现问题.当孩子只有一个水平但两个或两个以上的孩子崩溃时,我设法做到了.

Essentially I want to recurse through all the children and populate a new array with every parent and child in the nested arrays, I have tried array_merge, RecursiveIteratorIterator, itterator_to_array, array_map but it always comes unstuck on the recursion. I managed to do it when the children were only one level deep but two or more simply breaks down.

请帮助!

推荐答案

不是很难:

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;
}

这篇关于在PHP中展平JSON多深度数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆