Home > Backend Development > PHP Tutorial > 怎么由一维数组生成多维数组

怎么由一维数组生成多维数组

WBOY
Release: 2016-06-06 20:06:14
Original
1435 people have browsed it

一直不太明白,怎么能快捷的由一维数组生成多维数组:
我有一个字段是字符串,值可能是1或1-2或1-2-3-4-5...

例如如果是1-2-3-4,怎么能生成为多维数组:

<code>Array
(
    [1] => Array
        (
            [2] => Array
                (
                    [3] => Array
                        (
                            [4] => Array
                                (
                                )

                        )

                )

        )

)</code>
Copy after login
Copy after login

多谢

回复内容:

一直不太明白,怎么能快捷的由一维数组生成多维数组:
我有一个字段是字符串,值可能是1或1-2或1-2-3-4-5...

例如如果是1-2-3-4,怎么能生成为多维数组:

<code>Array
(
    [1] => Array
        (
            [2] => Array
                (
                    [3] => Array
                        (
                            [4] => Array
                                (
                                )

                        )

                )

        )

)</code>
Copy after login
Copy after login

多谢

<code class="php">// from https://segmentfault.com/q/1010000004647414
$str = '1-2-3-4';
$arr = explode('-', $str);
$last = null;
while($last = array_pop($arr)) {
    if(null != $last) {
       array_push($arr,[array_pop($arr)=>$last]);
    }
    if(count($arr)  Array
        (
            [1] => Array
                (
                    [2] => Array
                        (
                            [3] => 4
                        )

                )

        )

)*/</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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template