【问题标题】:How to convert all keys in a multi-dimenional array to snake_case?如何将多维数组中的所有键转换为snake_case?
【发布时间】:2010-11-29 11:47:56
【问题描述】:

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

我的现实生活中的阵列是巨大的,而且有很多层次。非常感谢任何有关如何解决此问题的帮助!

【问题讨论】:

  • 'snake case' 对我来说看起来像'小写'。每天都能学到新东西。
  • 在递归函数中使用 foreach()!
  • 好的,我现在看到了不同之处——snake_case 有下划线而不是空格。
  • @pavium:如果大写字符在单词的中间,则有一个_的区别......

标签: php arrays multidimensional-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;
}

【讨论】:

    【解决方案2】:

    创建一个类似的函数:

       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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        虽然这可能不是问题的确切答案,但我想在这里发布它,以供正在寻找优雅解决方案以更改多维 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));
        }
        

        【讨论】:

          【解决方案5】:

          您可以在数组键上运行 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]);
                  }
              }
          }
          

          【讨论】:

          • 谢谢你,它让我朝着正确的方向前进,但有几个问题。首先,$transformedKey 吐出了一些奇怪的结果,所以我稍微修改了该行。此外,由于某种原因,递归 if 语句需要位于存储新数组键的行上方。我将在下面发布我修改后的功能。
          • 刚刚注意到,现在应该修复了。
          【解决方案6】:

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

          【讨论】:

            【解决方案7】:

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

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

            您究竟需要什么具体的帮助?

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-07-09
              • 2011-08-24
              • 2019-04-03
              • 1970-01-01
              相关资源
              最近更新 更多