0

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);
2
  • And what you have tried so far. Post your attempts too.. Commented Sep 16, 2015 at 9:29
  • I have posted my attempt above Commented Sep 16, 2015 at 9:33

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.