递归将数组键从underscore_case转换为camelCase [英] Convert array keys from underscore_case to camelCase recursively

查看:198
本文介绍了递归将数组键从underscore_case转换为camelCase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不想出一种使用undescores(underscore_case)将数组键转换为camelCase的方法.由于我不知道将哪些数组馈入该方法,因此必须递归进行此操作.

I had to come up with a way to convert array keys using undescores (underscore_case) into camelCase. This had to be done recursively since I did not know what arrays will be fed to the method.

我想到了这个

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然后进行串联看起来很奇怪.

It does the job, but I think it could be done much better and more concisely. Multiple calls to preg_match and then concatenation just look weird.

您看到一种整理此方法的方法吗? 更重要的是,仅需一个调用preg_match就能完全执行相同的操作吗?看起来如何?

Do you see a way to tidy up this method? And more importantly, is it possible at all to do the same operation with just one call to preg_match ? How would that look like?

推荐答案

递归部分无法进一步简化或修饰.

The recursive part cannot be further simplified or prettified.

但是从下划线(又称为 snake_case )和camelCase 可以通过几种不同的方式完成:

But the conversion from underscore_case (also known as snake_case) and camelCase can be done in several different ways:

$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
);

选择您喜欢的!

这篇关于递归将数组键从underscore_case转换为camelCase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆