Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten multidimensional array concatenating keys [duplicate]

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!

like image 863
J. Bruni Avatar asked Mar 03 '12 12:03

J. Bruni


1 Answers

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

like image 83
Felix Kling Avatar answered Sep 29 '22 15:09

Felix Kling