这个让我很困惑。我搜索并找到了类似的问题,但似乎找不到任何与我的确切问题相匹配的问题。
在PHP中,我有一个这样的数组:
<?php
$array = array('one', 'two', 'three', 'four');
?>
我想把它转换成一个多维数组,如下所示:
<?php
$new_array = array('one' => array('two' => array('three' => array('four' => NULL))));
// or, to put another way:
$new_array['one']['two']['three']['four'] = NULL;
?>
记住,我不知道原始数组中有多少项,我需要一种递归创建多维关联数组的方法。
这似乎是一件容易的事,但我似乎搞不明白。
使用引用可以轻松做到这一点:
$out = array();
$cur = &$out;
foreach ($array as $value) {
$cur[$value] = array();
$cur = &$cur[$value];
}
$cur = null;
打印$out
应该给你:
Array
(
[one] => Array
(
[two] => Array
(
[three] => Array
(
[four] =>
)
)
)
)
function recursive_array_convert ($input, &$result = array()) {
$thisLevel = array_shift($input);
if (count($input)) {
if (!isset($result[$thisLevel]) || !is_array($result[$thisLevel])) {
$result[$thisLevel] = array();
}
recursive_array_convert($input, $result[$thisLevel]);
} else {
$result[$thisLevel] = NULL;
}
return $result;
}
这个函数应该给您很大的灵活性——您可以简单地将输入数组传递给第一个参数并在返回中获取结果,也可以将现有变量传递给第二个参数以填充结果。这意味着你可以在你的例子中实现你想要的:
$result = recursive_array_convert(array('one', 'two', 'three', 'four'));
或
recursive_array_convert(array('one', 'two', 'three', 'four'), $result);
乍一看,这个选项似乎没有什么意义,但请考虑以下内容:
$result = array();
recursive_array_convert(array('one', 'two', 'three', 'four'), $result);
recursive_array_convert(array('five', 'six', 'seven', 'eight'), $result);
print_r($result);
/* Output:
Array
(
[one] => Array
(
[two] => Array
(
[three] => Array
(
[four] =>
)
)
)
[five] => Array
(
[six] => Array
(
[seven] => Array
(
[eight] =>
)
)
)
)
*/
正如您所看到的,该函数可以用于在同一变量中创建任意数量的链。