开发者

Array to multidimensional array ... based on foo.bar.baz-dots in array key name

I have an array with "foo.bar.baz" as key names in the array. Is there a handy way to turn this array into a multidimensional array (using each "dot level" as key for the next array)?

  • Actual output: Array([foo.bar.baz] => 1, [qux] => 1)
  • Desired output: Array([foo][bar][baz] => 1, [qux] => 1)

Code example:

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


Solution:

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

Outputs:

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

        )

)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜