Skip to content

Instantly share code, notes, and snippets.

@saulopaiva
Last active December 31, 2015 21:39
Show Gist options
  • Select an option

  • Save saulopaiva/8048348 to your computer and use it in GitHub Desktop.

Select an option

Save saulopaiva/8048348 to your computer and use it in GitHub Desktop.
Function for flatten array
<?
/**
Transforms:
$data = array(
'user' => array(
'email' => '[email protected]',
'name' => 'Super User',
'address' => array(
'billing' => 'Street 1',
'delivery' => 'Street 2'
)
),
'post' => 'Hello, World!'
);
Into:
Array
(
[user.email] => [email protected]
[user.name] => Super User
[user.address.billing] => Street 1
[user.address.delivery] => Street 2
[post] => Hello, World!
)
*/
function flatten($array, $prefix = '', $glue = '.') {
$result = array();
foreach($array as $key=>$value) {
if(is_array($value)) {
$result = $result + flatten($value, $prefix . $key . $glue);
}
else {
$result[$prefix.$key] = $value;
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment