Skip to content

Instantly share code, notes, and snippets.

@KarelWintersky
Last active August 15, 2016 05:19
Show Gist options
  • Save KarelWintersky/8388af6b269ff2252e5095afc2800924 to your computer and use it in GitHub Desktop.
Save KarelWintersky/8388af6b269ff2252e5095afc2800924 to your computer and use it in GitHub Desktop.
Flatten array
/**
$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