Last active
August 15, 2016 05:19
-
-
Save KarelWintersky/8388af6b269ff2252e5095afc2800924 to your computer and use it in GitHub Desktop.
Flatten array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
$data = array( | |
'user' => array( | |
'email' => '[email protected]', | |
'name' => 'Super User', | |
'address' => array( | |
'billing' => 'Street 1', | |
'delivery' => 'Street 2' | |
) | |
), | |
'post' => 'Hello, World!' | |
); | |
transform this to: | |
$data = array( | |
'user.email' => '[email protected]', | |
'user.name' => 'Super User', | |
'user.address.billing' => 'Street 1', | |
'user.address.delivery' => 'Street 2', | |
'post' => 'Hello, World!' | |
); | |
*/ | |
/** | |
* @param $array | |
* @param string $prefix | |
* @param string $suffix | |
* @return array|null | |
*/ | |
function array_flatten($array, $prefix = '', $suffix = '/') | |
{ | |
$result = array(); | |
if (!is_array($array)) return null; | |
foreach ($array as $key => $value) { | |
if (is_array($value)) | |
$result = array_merge($result, array_flatten($value, $prefix . $key . $suffix, $suffix)); | |
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