我想从一个数组构建一个多维数组。例如,我想
$test = array (
0 => 'Tree',
1 => 'Trunk',
2 => 'Branch',
3 => 'Limb',
4 => 'Apple',
5 => 'Seed'
);成为
$test =
array (
'Tree' => array (
'Trunk' => array (
'Branch' => array (
'Limb' => array (
'Apple' => array (
'Seed' => array ()
)
)
)
)
)
);或者更简单
$result[Tree][Trunk][Branch][Limb][Apple][Seed] = null;我试图用递归函数来实现这一点,但是我达到了内存限制,所以我显然做错了。
<?php
$test = array (
0 => 'Tree',
1 => 'Trunk',
2 => 'Branch',
3 => 'Limb',
4 => 'Apple',
5 => 'Seed'
);
print_r($test);
print "results of function";
print_r(buildArray($test));
function buildArray (&$array, &$build = null)
{
if (count($array) > 0)
{
//create an array, pass the array to itself removing the first value
$temp = array_values($array);
unset ($temp[0]);
$build[$array[0]] = $temp;
buildArray($build,$temp);
return $build;
}
return $build;
}发布于 2015-05-15 18:36:02
这个函数可以递归地工作,并完成了以下任务:
function buildArray($from, $to = []) {
if (empty($from)) { return null; }
$to[array_shift($from)] = buildArray($from, $to);
return $to;
}在您的代码中,我希望您看到一个错误。在第一次迭代中,您正在与$build交谈,就好像它在数组中的位置一样,而您已经将它默认为null。
发布于 2015-05-15 18:33:03
下面是一种使用foreach和不使用递归的方法,它可以工作:
function buildArray($array)
{
$new = array();
$current = &$new;
foreach($array as $key => $value)
{
$current[$value] = array();
$current = &$current[$value];
}
return $new;
}[ 演示 ]
现在你的功能..。首先,在不将$build[$array[0]]定义为数组的情况下使用E_NOTICE首先生成一个E_NOTICE。其次,您的函数将进入无限递归,因为您实际上并不是在修改$array ($temp不一样),因此count($array) > 0将是永恒的。
即使您正在修改$array,也不能再使用$array[0]了,因为您取消了设置,而且索引也不会向上滑动。为此,你需要array_shift。
在此之后,您将$build和$temp传递给您的函数,这将导致进一步的结果,因为您现在将$build分配给$temp,因此在已经无限循环的循环中创建了另一个循环。
我试图在您的代码中修复上述所有内容,但最终意识到,我的代码现在几乎完全是来自佩瓦拉的回答的代码,只是具有不同的变量名,所以.就这样。
发布于 2015-05-15 18:36:06
这似乎很容易
$res = array();
$i = count($test);
while ($i)
$res = array($test[--$i] => $res);
var_export($res);返回
array ( 'Tree' => array ( 'Trunk' => array ( 'Branch' => array ( 'Limb' => array ( 'Apple' => array ( 'Seed' => array ( ), ), ), ), ), ), )https://stackoverflow.com/questions/30266229
复制相似问题