数组到多维数组...基于数组键名中的foo.bar.baz-dots

时间:2011-07-10 07:38:37

标签: php recursion multidimensional-array

我有一个数组,其中“foo.bar.baz”作为数组中的键名。是否有方便的方法将此数组转换为多维数组(使用每个“点级”作为下一个数组的键)?

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

代码示例:

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

1 个答案:

答案 0 :(得分:3)

<强>解决方案:

<?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
                )

        )

)