转换的一维数组到一个多维数组相关

转换的一维数组到一个多维数组相关

问题描述:

这其中有我难住了。我搜索,发现类似的问题,但我似乎无法找到符合我确切的问题,任何问题。

This one has me stumped. I've searched and found similar questions but I can't seem to find any questions that match my exact problem.

在PHP中,我有一个数组,像这样:

In PHP, I have an array like so:

<?php
   $array = array('one', 'two', 'three', 'four');
?>

我想它转换成一个多维数组类似如下:

I want to convert this into a multi-dimensional array like the following:

<?php
   $new_array = array('one' => array('two' => array('three' => array('four' => NULL))));
   // or, to put another way:
   $new_array['one']['two']['three']['four'] = NULL;
?>

铭记,我不知道有多少项目将原来的阵中,我需要一种方法来递归创建多维数组相关

Bearing in mind I do not know how many items will be in the original array, I need a way to recursively create a multi-dimensional associated array.

这似乎是一件容易的事,但我似乎无法想出解决办法。

It seemed like an easy thing to do, but I can't seem to figure this out.

您可以通过引用做到这一点很容易:

You can do that easily with references:

$out = array();
$cur = &$out;
foreach ($array as $value) {
    $cur[$value] = array();
    $cur = &$cur[$value];
}
$cur = null;

印刷 $退出应该给你:

Array
(
    [one] => Array
        (
            [two] => Array
                (
                    [three] => Array
                        (
                            [four] => 
                        )
                )
        )
)