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

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:09:17
Original
927 people have browsed it

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

转为

$brr = array(

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

);

回复内容:

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

转为

$brr = array(

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

);

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

结果为

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

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

<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>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template