我不得不想出一种方法,将使用下划线 (underscore_case) 的数组键转换为驼峰式。这必须以递归方式完成,因为我不知道哪些数组将被提供给该方法。
我想到了这个:
private function convertKeysToCamelCase($apiResponseArray)
{
$arr = [];
foreach ($apiResponseArray as $key => $value) {
if (preg_match('/_/', $key)) {
preg_match('/[^_]*/', $key, $m);
preg_match('/(_)([a-zA-Z]*)/', $key, $v);
$key = $m[0] . ucfirst($v[2]);
}
if (is_array($value))
$value = $this->convertKeysToCamelCase($value);
$arr[$key] = $value;
}
return $arr;
}
它完成了工作,但我认为它可以做得更好、更简洁。多次调用 preg_match
然后串联看起来很奇怪。
你有没有办法整理这个方法?
更重要的是,是否有可能只通过 一次 调用 preg_match
来执行相同的操作?那会是什么样子?
最佳答案
递归部分无法进一步简化或美化。
但是从 underscore_case(也称为 snake_case )和 camelCase 的转换可以通过几种不同的方式完成:
$key = 'snake_case_key';
// split into words, uppercase their first letter, join them,
// lowercase the very first letter of the name
$key = lcfirst(implode('', array_map('ucfirst', explode('_', $key))));
或
$key = 'snake_case_key';
// replace underscores with spaces, uppercase first letter of all words,
// join them, lowercase the very first letter of the name
$key = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
或
$key = 'snake_case_key':
// match underscores and the first letter after each of them,
// replace the matched string with the uppercase version of the letter
$key = preg_replace_callback(
'/_([^_])/',
function (array $m) {
return ucfirst($m[1]);
},
$key
);
选择你最喜欢的!
关于php - 递归地将数组键从 underscore_case 转换为 camelCase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31274782/