从多个不同的数组创建多维数组

时间:2019-05-24 07:24:23

标签: php arrays

我怀疑这个问题之前已经回答过,但是我已经挖了这个伟大的论坛,并徒劳地寻求答案。....

我有3个看起来像这样的数组:

Array
(
    [1] => 19
    [2] => 2
    [3] => 2018
)

Array
(
    [1] => 19
    [2] => 1
    [3] => 2017
)

Array
(
    [1] => 18
    [2] => 2
    [3] => 2016
)

我想将这3个数组转换为多维数组,如下所示:

$mynewArray =  Array(

    [0] =>array(
        [1] => 19
        [2] => 2
        [3] => 2018
    )

    [1] =>array(
        [1] => 19
        [2] => 1
        [3] => 2017
    )

    [2] => array(
        [1] => 18
        [2] => 2
        [3] => 2016

    )
    )

我如何在PHP中实现这一目标?

2 个答案:

答案 0 :(得分:1)

Demo Link

您只需将其添加到父数组中,如下所示,

$arr1 = [1 => 19, 2 => 2, 3 => 2018];
$arr2 = [1 => 19, 2 => 1, 3 => 2017];
$arr3 = [1 => 18, 2 => 2, 3 => 2016];
$mynewArray = [$arr1,$arr2,$arr3];
print_r($mynewArray);

输出

Array
(
    [0] => Array
        (
            [1] => 19
            [2] => 2
            [3] => 2018
        )

    [1] => Array
        (
            [1] => 19
            [2] => 1
            [3] => 2017
        )

    [2] => Array
        (
            [1] => 18
            [2] => 2
            [3] => 2016
        )

)

答案 1 :(得分:0)

您还可以通过以下方式将子数组追加到父数组中

 $array1 = array("1"=>"1","2"=>"2","3"=>"3");
 $array2 = array("1"=>"1","2"=>"2","3"=>"3");

 $newarray = array($array1,$array2);