I got an array and would like to convert its array keys from camel case to underscore case. How this could be done?
$before = ['ThisIsATest' => 'Something', 'cheeseCake' => 'Something else'];
$after = ['this_is_a_test' => 'Something', 'cheese_cake' => 'Something else'];
I primarily would like to know how to update array keys!
Based on your input i created the following two functions:
function camelToUnderscore($string)
{
if (is_numeric($string)) {
return $string;
}
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $string, $matches);
$ret = $matches[0];
foreach ($ret as &$match) {
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
function keysCamelToUnderscore(array $array)
{
$newArray = [];
foreach ($array AS $key => $value) {
if (!is_array($value)) {
unset($array[$key]);
$newArray[camelToUnderscore($key)] = $value;
} else {
unset($array[$key]);
$newArray[camelToUnderscore($key)] = keysCamelToUnderscore($value);
}
}
return $newArray;
}