递归地将多维数组中的所有key转换为snake_case

问题描述 投票:0回答:8

我正在尝试将多维数组的键从camelCase或StudlyCase/PascalCase转换为snake_case,但更复杂的是,某些键有一个前导感叹号,我想将其删除。

例如:

$array = array(
  '!AccountNumber' => '00000000',
  'Address' => array(
    '!Line1' => '10 High Street',
    '!line2' => 'London'));

我想转换为:

$array = array(
  'account_number' => '00000000',
  'address' => array(
    'line1' => '10 High Street',
    'line2' => 'London'));

我的现实生活中的数组非常巨大并且深入很多层次。

php recursion multidimensional-array key camelcasing
8个回答
14
投票

这是我使用的修改后的功能,摘自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;
}

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;
}

1
投票

您可以在数组键上运行 foreach,这样您就可以就地重命名键:

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
投票

虽然这可能不是问题的准确答案,但我想将其发布在这里,供那些正在寻找优雅的解决方案来更改多维 PHP 数组中的关键案例的人们使用。您还可以调整它以更改一般的数组键。只需调用不同的函数而不是 array_change_key_case_recursive

// converts all keys in a multidimensional array to lower or upper case
function array_change_key_case_recursive($arr, $case=CASE_LOWER)
{
  return array_map(function($item)use($case){
    if(is_array($item))
        $item = array_change_key_case_recursive($item, $case);
    return $item;
  },array_change_key_case($arr, $case));
}

1
投票

创建一个如下函数:

   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;
}

并这样称呼它:

$newArray = convertToCamelCase($array);

工作示例请参阅此


1
投票
<?php

class Maison {
    
    public $superficieAll_1;
    public $addressBook;
    
}

class Address { 
    public $latitudeAmi;
    public $longitude;
}

$maison = new Maison();
$maison->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 <br>";
        unset($array[$key]);
        $transformedKey = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', ltrim($key, '!')));
        $array[$transformedKey] = $value;  
        // echo "$transformedKey update <br>";
        if (is_array($value)) {
            $array[$transformedKey] = transformKeys($value);
        }
    }
    return $array;
}

0
投票

我想说你必须编写一个函数来复制数组(一级),并且如果任何值是数组(递归函数),则让该函数调用自身。

  • 使用trim()可以轻松删除感叹号
  • 中间大写字符前的下划线可以使用正则表达式添加
  • 添加下划线后可以将整个按键转为小写

您到底需要什么具体帮助?


0
投票

为了避免改变原始数组并返回具有重新格式化键的新数组,请使用递归函数而不通过引用进行修改,并在每个级别返回新数组。

代码:(演示

function snakeCaseKeys($array): array
{
    $result = [];
    foreach ($array as $k => $v) {
        $k = strtolower(
                 preg_replace(
                     '/[a-z]\K(?=[A-Z])/',
                     '_',
                     ltrim($k, '!')
                 )
             );
        $result[$k] = is_array($v) ? snakeCaseKeys($v) : $v;
    }
    return $result;
}

var_export(
    snakeCaseKeys($array)
);

测试数据:

$array = [
    '!AccountNumber' => '00000000',
    'Address' => [
        '!Line1' => '10 High Street',
        'deeperSubArrayToRekey' => [
            'camelCase' => 'starts with lowercase',
            'PascalCase' => 'starts with uppercase',
            'StudlyCase' => 'is a synonym for PascalCase',
            '!!!!snake_case' => 'is already fully lowercase',
        ],
        '!line2' => 'London',
        'Line1' => 'will overwrite 10 High Street',
    ]
];

输出:

array (
  'account_number' => '00000000',
  'address' => 
  array (
    'line1' => 'will overwrite 10 High Street',
    'deeper_sub_array_to_rekey' => 
    array (
      'camel_case' => 'starts with lowercase',
      'pascal_case' => 'starts with uppercase',
      'studly_case' => 'is a synonym for PascalCase',
      'snake_case' => 'is already fully lowercase',
    ),
    'line2' => 'London',
  ),
)
© www.soinside.com 2019 - 2024. All rights reserved.