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

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

    You can run a foreach on the arrays keys, this way you'll rename the keys in-place:

    function transformKeys(&$array) {
        foreach (array_keys($array) as $key) {
            # This is what you actually want to do with your keys:
            #  - remove exclamation marks at the front
            #  - camelCase to snake_case
            $transformedKey = ltrim($key, '!');
            $transformedKey = strtolower($transformedKey[0] . preg_replace('/[A-Z]/', '_$0', substr($transformedKey, 1)));
            # Store with new key
            $array[$transformedKey] = &$array[$key];
            unset($array[$key]);
            # Work recursively
            if (is_array($array[$transformedKey])) {
                transformKeys($array[$transformedKey]);
            }
        }
    }
    

提交回复
热议问题