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

前端 未结 7 2380
無奈伤痛
無奈伤痛 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

    superficieAll_1 = 80;
    $maison->addressBook->longitudeAmi = 2;
    $maison->addressBook->latitude = 4;
    
    $returnedArray = transformation($maison);
    print_r($returnedArray);
    
    function transformation($obj){
        //object to array
        $array = json_decode(json_encode((array) $obj),true);
        //now transform all array keys
        return transformKeys($array);
    }    
    
    function transformKeys($array)
    {
        foreach ($array as $key => $value){
            // echo "$key 
    "; unset($array[$key]); $transformedKey = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', ltrim($key, '!'))); $array[$transformedKey] = $value; // echo "$transformedKey update
    "; if (is_array($value)) { $array[$transformedKey] = transformKeys($value); } } return $array; }

提交回复
热议问题