PHP创建嵌套数组中每个值的面包屑列表

PHP创建嵌套数组中每个值的面包屑列表,php,arrays,recursion,hierarchy,breadcrumbs,Php,Arrays,Recursion,Hierarchy,Breadcrumbs,我有一个如下所示的数组: [ 'applicant' => [ 'user' => [ 'username' => true, 'password' => true, 'data' => [ 'value' => true, 'anotherValue' => true ]

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

[
    '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);

此函数满足您的要求:

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

您可以看到它正在运行。

以及您到目前为止所做的尝试。我已经把我的尝试贴在上面了