我有一个数组,其中“foo.bar.baz”作为数组中的键名。是否有方便的方法将此数组转换为多维数组(使用每个“点级”作为下一个数组的键)?
代码示例:
$arr = array("foo.bar.baz" => 1, "qux" => 1);
print_r($arr);
答案 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
)
)
)