php - Convert array keys from underscore_case to camelCase recursively -


i had come way convert array keys using undescores (underscore_case) camelcase. had done recursively since did not know arrays fed method.

i came this:

private function convertkeystocamelcase($apiresponsearray) {     $arr = [];     foreach ($apiresponsearray $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; } 

it job, think done better , more concisely. multiple calls preg_match , concatenation weird.

do see way tidy method? , more importantly, possible @ same operation one call preg_match ? how like?

the recursive part cannot further simplified or prettified.

but conversion underscore_case (also known snake_case) , camelcase can done in several different ways:

$key = 'snake_case_key'; // split words, uppercase first letter, join them,  // lowercase first letter of name $key = lcfirst(implode('', array_map('ucfirst', explode('_', $key)))); 

or

$key = 'snake_case_key'; // replace underscores spaces, uppercase first letter of words, // join them, lowercase first letter of name $key = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key)))); 

or

$key = 'snake_case_key': // match underscores , first letter after each of them, // replace matched string uppercase version of letter $key = preg_replace_callback(     '/_([^_])/',     function (array $m) {         return ucfirst($m[1]);     },     $key ); 

pick favorite!


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -