PHP创建嵌套数组中每个值的面包屑列表 [英] PHP Create breadcrumb list of every value in nested array

查看:53
本文介绍了PHP创建嵌套数组中每个值的面包屑列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像下面的数组:

I have an array that looks like the following:

[
    'applicant' => [
        'user' => [
            'username' => true,
            'password' => true,
            'data' => [
                'value' => true,
                'anotherValue' => true
            ]
        ]
    ]
]

我想做的就是将该数组转换为看起来像这样的数组:

What I want to be able to do is convert that array into an array that looks like:

[
    'applicant.user.username',
    'applicant.user.password',
    'applicant.user.data.value',
    'applicant.user.data.anotherValue'
]

基本上,我需要以某种方式遍历嵌套数组,并且每次到达叶节点时,将到该节点的整个路径保存为点分隔的字符串.

Basically, I need to somehow loop through the nested array and every time a leaf node is reached, save the entire path to that node as a dot separated string.

只有以true为值的键是叶节点,其他所有节点将始终是数组.我将如何实现这一目标?

Only keys with true as a value are leaf nodes, every other node will always be an array. How would I go about accomplishing this?

修改

这是我到目前为止尝试过的,但是没有给出预期的结果:

This is what I have tried so far, but doesnt give the intended results:

    $tree = $this->getTree(); // Returns the above nested array
    $crumbs = [];

    $recurse = function ($tree, &$currentTree = []) use (&$recurse, &$crumbs)
    {
        foreach ($tree as $branch => $value)
        {
            if (is_array($value))
            {
                $currentTree[] = $branch;
                $recurse($value, $currentTree);
            }
            else
            {
                $crumbs[] = implode('.', $currentTree);
            }
        }
    };

    $recurse($tree);

推荐答案

此功能可以满足您的要求:

This function does what you want:

function flattenArray($arr) {
    $output = [];

    foreach ($arr as $key => $value) {
        if (is_array($value)) {
            foreach(flattenArray($value) as $flattenKey => $flattenValue) {
                $output["${key}.${flattenKey}"] = $flattenValue;
            }
        } else {
            $output[$key] = $value;
        }
    }

    return $output;
}

您可以在此处看到它运行.

这篇关于PHP创建嵌套数组中每个值的面包屑列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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