Convert array keys from underscore_case to camelCase recursively

前端 未结 6 2130
一向
一向 2020-12-31 17:59

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

6条回答
  •  [愿得一人]
    2020-12-31 18:13

    The recursive part cannot be further simplified or prettified.

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

    or

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

    or

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

    Pick your favorite!

提交回复
热议问题