如何将多维数组中的所有键转换为snake_case?

aar*_*ell 9 php arrays multidimensional-array

我试图将多维数组的键从CamelCase转换为snake_case,增加的复杂性是某些键有一个我想删除的感叹号.

例如:

$array = array(
  '!AccountNumber' => '00000000',
  'Address' => array(
    '!Line1' => '10 High Street',
    '!line2' => 'London'));
Run Code Online (Sandbox Code Playgroud)

我想转换为:

$array = array(
  'account_number' => '00000000',
  'address' => array(
    'line1' => '10 High Street',
    'line2' => 'London'));
Run Code Online (Sandbox Code Playgroud)

我现实生活中的阵列非常庞大,深入人心.任何帮助如何处理这一点非常感谢!

aar*_*ell 11

这是我使用的修改函数,取自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;
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*n49 5

这是亚伦的更通用的版本。这样你就可以为所有按键插入你想要操作的功能。我假设了一个静态类。

public static function toCamelCase ($string) {
  $string_ = str_replace(' ', '', ucwords(str_replace('_',' ', $string)));
  return lcfirst($string_);
}

public static function toUnderscore ($string) {
  return strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $string));
}

// http://stackoverflow.com/a/1444929/632495
function transformKeys($transform, &$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 = call_user_func($transform, $key);
    # Work recursively
    if (is_array($value)) self::transformKeys($transform, $value);
    # Store with new key
    $array[$transformedKey] = $value;
    # Do not forget to unset references!
    unset($value);
  endforeach;
}

public static function keysToCamelCase ($array) {
  self::transformKeys(['self', 'toCamelCase'], $array);
  return $array;
}

public static function keysToUnderscore ($array) {
  self::transformKeys(['self', 'toUnderscore'], $array);
  return $array;
}
Run Code Online (Sandbox Code Playgroud)