解決方案:
<?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
)
)
)
+1我無法找出答案:) – AlienWebguy
尼斯。你可以把它放到一個函數中嗎?像array_dotkey($ value,&$ tmparr){...} –
@Kristoffer Bohmann - 你當然可以,但我會建議創建一個接受數組的函數。我會更新答案。 –