Flatten multidimensional array concatenating keys [duplicate] Flatten multidimensional array concatenating keys [duplicate] arrays arrays

Flatten multidimensional array concatenating keys [duplicate]


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


Thanks for all the given answers.

I have transformed it in the following, which is an improved version. It eliminates the need of a root prefix, does not need to use references, it is cleaner to read, and it has a better name:

function array_flat($array, $prefix = ''){    $result = array();    foreach ($array as $key => $value)    {        $new_key = $prefix . (empty($prefix) ? '' : '.') . $key;        if (is_array($value))        {            $result = array_merge($result, array_flat($value, $new_key));        }        else        {            $result[$new_key] = $value;        }    }    return $result;}


Try this

<?php$data = array(    'user' => array(        'email'   => 'user@example.com',        'name'    => 'Super User',        'address' => array(            'billing' => 'Street 1',            'delivery' => 'Street 2'        )    ),    'post' => 'Hello, World!');function prefixKey($prefix, $array){    $result = array();    foreach ($array as $key => $value)    {        if (is_array($value))            $result = array_merge($result, prefixKey($prefix . $key . '.', $value));        else            $result[$prefix . $key] = $value;    }       return $result;}var_dump(prefixKey('', $data));?>

Outputs

array  'user.email' => string 'user@example.com' (length=16)  'user.name' => string 'Super User' (length=10)  'user.address.billing' => string 'Street 1' (length=8)  'user.address.delivery' => string 'Street 2' (length=8)  'post' => string 'Hello, World!' (length=13)