PHP Create breadcrumb list of every value in nested array

吃可爱长大的小学妹 提交于 2019-11-27 08:52:52

问题


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.

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?

edit

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

回答1:


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

You can see it running here.



来源:https://stackoverflow.com/questions/32604503/php-create-breadcrumb-list-of-every-value-in-nested-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!