如何在 PHP 中从数组中创建嵌套数组

2022-01-24 00:00:00 arrays nested iteration php

说,我们有一个数组:array(1,2,3,4,...)我想将其转换为:

Say, we have an array: array(1,2,3,4,...) And I want to convert it to:

array(
    1=>array(
        2=>array(
            3=>array(
                4=>array()
            )
        )
    )
)

有人可以帮忙吗?
谢谢

Can anybody help?
Thanks

编辑最好有迭代的解决方案.

EDIT It would be good to have the solution with iterations.

推荐答案

$x = count($array) - 1;
$temp = array();
for($i = $x; $i >= 0; $i--)
{
    $temp = array($array[$i] => $temp);
}

相关文章