【问题标题】:Array to multidimensional array ... based on foo.bar.baz-dots in array key name数组到多维数组...基于数组键名中的 foo.bar.baz-dots
【发布时间】:2011-07-10 07:38:37
【问题描述】:

我有一个数组,其中“foo.bar.baz”作为数组中的键名。有没有一种方便的方法可以将这个数组变成一个多维数组(使用每个“点级别”作为下一个数组的键)?

  • 实际输出:Array([foo.bar.baz] => 1, [qux] => 1)
  • 所需输出:Array([foo][bar][baz] => 1, [qux] => 1)

代码示例:

$arr = array("foo.bar.baz" => 1, "qux" => 1);
print_r($arr);

【问题讨论】:

    标签: php recursion multidimensional-array


    【解决方案1】:

    解决方案:

    <?php
    
    $arr = array('foo.bar.baz' => 1, 'qux' => 1);
    
    function array_dotkey(array $arr)
    {
      // Loop through each key/value pairs.
      foreach ( $arr as $key => $value )
      {
        if ( strpos($key, '.') !== FALSE )
        {
          // Reference to the array.
          $tmparr =& $arr;
    
          // Split the key by "." and loop through each value.
          foreach ( explode('.', $key) as $tmpkey )
          {
            // Add it to the array.
            $tmparr[$tmpkey] = array();
    
            // So that we can recursively continue adding values, change $tmparr to a reference of the most recent key we've added.
            $tmparr =& $tmparr[$tmpkey];
          }
    
          // Set the value.
          $tmparr = $value;
    
          // Remove the key that contains "." characters now that we've added the multi-dimensional version.
          unset($arr[$key]);
        }
      }
    
      return $arr;
    }
    
    $arr = array_dotkey($arr);
    print_r($arr);
    

    输出:

    Array
    (
        [qux] => 1
        [foo] => Array
            (
                [bar] => Array
                    (
                        [baz] => 1
                    )
    
            )
    
    )
    

    【讨论】:

    • 不错。你能把它变成一个函数吗?像 array_dotkey($value,&$tmparr) { ... }
    • @Kristoffer Bohmann - 你当然可以,但我只建议创建一个接受数组的函数。我会更新答案。
    • 喜欢每一行的评论(:D 笑话)
    猜你喜欢
    • 1970-01-01
    • 2015-01-06
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多