Как преобразовать все ключи в массиве multi-dimenional в snake_case?

Как насчет

List<object> collection = new List<object>((IEnumerable)myObject);
9
задан aaronrussell 18 September 2009 в 13:14
поделиться

3 ответа

Это модифицированная функция, которую я использовал, взято из ответа soulmerge:

function transformKeys(&$array)
{
  foreach (array_keys($array) as $key):
    # Working with references here to avoid copying the value,
    # since you said your data is quite large.
    $value = &$array[$key];
    unset($array[$key]);
    # This is what you actually want to do with your keys:
    #  - remove exclamation marks at the front
    #  - camelCase to snake_case
    $transformedKey = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', ltrim($key, '!')));
    # Work recursively
    if (is_array($value)) transformKeys($value);
    # Store with new key
    $array[$transformedKey] = $value;      
    # Do not forget to unset references!
    unset($value);
  endforeach;
}
11
ответ дан 4 December 2019 в 11:06
поделиться

I'd say you would have to write a function to copy the array (one level) and have that function call itself if any of the values is an array (a recursive function).

  • The exclamation marks are easily removed using trim()
  • The underscore before the uppercase characters in the middle can be added using a regex
  • After adding the underscore, the whole key can be converted to lower case

What exactly do you need any specific help with?

0
ответ дан 4 December 2019 в 11:06
поделиться

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]);
        }
    }
}
1
ответ дан 4 December 2019 в 11:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: