Convert array keys from underscore_case to camelCase recursively

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

    Here is another approach taking advantage of array_walk_recursive() and preg_replace_callback methods in the simplest possible way :)

    function convertKeysToCamelCase($array)
    {
        $result = [];
    
        array_walk_recursive($array, function ($value, &$key) use (&$result) {
            $newKey = preg_replace_callback('/_([a-z])/', function ($matches) {
                return strtoupper($matches[1]);
            }, $key);
    
            $result[$newKey] = $value;
        });
    
        return $result;
    }
    

提交回复
热议问题