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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With