Convert array keys from underscore_case to camelCase recursively

前端 未结 6 2089
一向
一向 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

    Try preg_replace_callback():

    $key = preg_replace_callback('/_([a-z]*)/', function($matches) {
        return ucfirst($matches[1]);
    }), $key);
    

    A couple notes:

    • you only need to look for [a-z] because [A-Z] will already be capitalized
    • * 0+ repetition was used in case we have a situation like camel_$case, I assumed that the _ should still be replaced
    • here's a demo of the expression that doesn't run the ucfirst() on the first match group

提交回复
热议问题