How to convert all keys in a multi-dimenional array to snake_case?

前端 未结 7 2303
無奈伤痛
無奈伤痛 2021-02-14 09:08

I am trying to convert the keys of a multi-dimensional array from CamelCase to snake_case, with the added complication that some keys have an exclamation mark that I\'d like rem

7条回答
  •  有刺的猬
    2021-02-14 09:40

    Create a function like:

       function convertToCamelCase($array){
    
               $finalArray     =       array();
    
               foreach ($array as $key=>$value):
    
                        if(strpos($key, "_"))
                                $key                    =       lcfirst(str_replace("_", "", ucwords($key, "_"))); //let's convert key into camelCase
    
    
                        if(!is_array($value))
                                $finalArray[$key]       =       $value;
                        else
                                $finalArray[$key]       =       $this->_convertToCamelCase($value );
                endforeach;
    
                return $finalArray;
    }
    

    and call this like:

    $newArray = convertToCamelCase($array);
    

    for working example see this

提交回复
热议问题