php - 递归地将数组键从 underscore_case 转换为 camelCase

标签 php arrays regex recursion

我不得不想出一种方法,将使用下划线 (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/

相关文章:

java - 使用无参数构造函数添加到数组

php - 如何使用php从数组中获取数组中的键和值

当 R 中以小写字母开头时,从数据框单元格中删除第一个单词

regex - 偶数个 0 或奇数个 1 的二进制数的最短正则表达式

php - 这两个 IF block 中哪个是更好的编码实践?

php - jQ Grid 编辑表单的问题不向 SQL 数据库发送请求

javascript - 尝试访问js文件中的ejs数组

regex - Bigquery 标准方言 REGEXP_REPLACE 输入类型

php - Magento 网格问题

php - 如何在存储过程中添加where条件作为参数?