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

时间:2009-09-18 13:14:12

标签: php arrays multidimensional-array

我正在尝试将多维数组的键从CamelCase转换为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'));

我现实生活中的阵列非常庞大并且深入了解多层次。任何有关如何处理此问题的帮助都非常感谢!

7 个答案:

答案 0 :(得分:10)

这是我使用过的修改过的函数,取自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;
}

答案 1 :(得分:4)

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

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

答案 2 :(得分:3)

虽然这可能不是问题的准确答案,但我想在此处发布,以便为那些在多维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));
}

答案 3 :(得分: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]);
        }
    }
}

答案 4 :(得分: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);

表示工作示例see this

答案 5 :(得分:0)

我会说你必须写一个函数来复制数组(一个级别),并且如果任何值是一个数组(一个递归函数),那么该函数会调用它自己。

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

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

答案 6 :(得分:0)

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