我有一个数组"foo.bar "。作为数组中的关键名。是否有一种方便的方法将此数组转换为多维数组(使用每个"点级别"作为下一个数组的关键)?
- 实际输出:Array([foo.bar.][x] => 1, [x] => 1)
- 期望输出值:数组((foo)(酒吧)(baz) => 1, [qux] => 1)
代码示例:
$arr = array("foo.bar.baz" => 1, "qux" => 1);
print_r($arr);
解决方案:
<?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
)
)
)