【问题标题】:PHP Create breadcrumb list of every value in nested arrayPHP创建嵌套数组中每个值的面包屑列表
【发布时间】:2015-09-16 09:21:36
【问题描述】:

我有一个如下所示的数组:

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

我想要做的是将该数组转换为如下所示的数组:

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

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

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

编辑

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

    $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);

【问题讨论】:

  • 到目前为止你已经尝试过什么。也发布你的尝试..
  • 我已经在上面发布了我的尝试

标签: php arrays recursion hierarchy breadcrumbs


【解决方案1】:

这个函数做你想做的:

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

你可以看到它正在运行here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多