Skip to content

Instantly share code, notes, and snippets.

@jan-j
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jan-j/ce8a671521c26021e140 to your computer and use it in GitHub Desktop.
Save jan-j/ce8a671521c26021e140 to your computer and use it in GitHub Desktop.
array_flatten_keys function
/**
* @param array $array
* @param string|null $keyPrefix
* @param string $format 'dot'|'form'
* @return array
*/
function array_flatten_keys($array, $keyPrefix = null, $format = 'dot')
{
$newArray = array();
foreach ($array as $key => $value) {
if (is_null($keyPrefix)) {
$fullKey = $key;
} else {
$fullKey = $keyPrefix;
if ($format === 'dot') {
$fullKey .= '.' . (string)$key;
} elseif ($format === 'form') {
$fullKey .= '[' . (string)$key . ']';
} else {
new InvalidArgumentException('Unknown format');
}
}
if (is_array($value)) {
$newArray = array_merge(
$newArray,
array_flatten_keys($value, $fullKey, $format)
);
} else {
$newArray[$fullKey] = $value;
}
}
return $newArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment