Last active
August 29, 2015 14:08
-
-
Save jan-j/ce8a671521c26021e140 to your computer and use it in GitHub Desktop.
array_flatten_keys function
This file contains hidden or 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
/** | |
* @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