转换的一维数组到一个多维数组相关 [英] Converting an single-dimension array into a multi-dimensional associated array

查看:102
本文介绍了转换的一维数组到一个多维数组相关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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] => 
                        )
                )
        )
)

这篇关于转换的一维数组到一个多维数组相关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆