Home >Backend Development >PHP Tutorial >一维数组 转 多维数组问题,乱了!

一维数组 转 多维数组问题,乱了!

WBOY
WBOYOriginal
2016-06-06 20:09:17896browse

$arr = array('a','b','c','d');

转为

$brr = array(

<code>'a'=>array(
    'b'=>array(
        'c'=>array(
            'd'=>array()
        )
    )
)</code>

);

回复内容:

$arr = array('a','b','c','d');

转为

$brr = array(

<code>'a'=>array(
    'b'=>array(
        'c'=>array(
            'd'=>array()
        )
    )
)</code>

);

<code><?php $arr = ['a', 'b', 'c', 'd'];
$child = array();
$res = [];
while($v = array_pop($arr)) {
    $res = [$v => $child];
    $child = $res;
}
print_r($res);</code>

结果为

<code>Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => Array
                        (
                            [d] => Array
                                (
                                )
                        )
                )
        )
)</code>

看到结构想到了递归,具体代码如下:

<code>
    function toMany ($arr) {
        $res = array();
        burnArr($res, $arr);
        return $res;
    }
    
    function burnArr (&$arr, $keys) {
        if ( !empty($keys) ) {
            $val = array_shift($keys);
            $arr[$val] = array();
            burnArr($arr[$val], $keys);
        } else {
            return ;
        }
    }
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn