Flatten multidimensional array concatenating keys

J. Bruni picture J. Bruni · Mar 3, 2012 · Viewed 26.1k times · Source

Possible Duplicate:
PHP convert nested array to single array while concatenating keys?
Get array's key recursively and create underscore seperated string

Please, read the whole question before answering.

I have this multidimensional array:

$data = array(
    'user' => array(
        'email'   => '[email protected]',
        'name'    => 'Super User',
        'address' => array(
            'billing' => 'Street 1',
            'delivery' => 'Street 2'
        )
    ),
    'post' => 'Hello, World!'
);

I want it flatten, transformed into:

$data = array(
    'user.email' => '[email protected]',
    'user.name'  => 'Super User',
    'user.address.billing'  => 'Street 1',
    'user.address.delivery' => 'Street 2',
    'post'       => 'Hello, World!'
);

Important:

  • The keys are very important to me. I want them concatenated, separated by periods.

  • It should work with any level of nesting.

Thank you!

Answer

Felix Kling picture Felix Kling · Mar 3, 2012

Something like this should work:

function flatten($array, $prefix = '') {
    $result = array();
    foreach($array as $key=>$value) {
        if(is_array($value)) {
            $result = $result + flatten($value, $prefix . $key . '.');
        }
        else {
            $result[$prefix . $key] = $value;
        }
    }
    return $result;
}

DEMO