向数组添加一行

时间:2018-04-18 10:46:42

标签: php arrays

我正在尝试创建一个函数,以便创建一个数组。

我能够创建这个数组:

        $result = [ 'data' =>
        [0 =>
            [
                'months' => $months[0],
                'years' => $years[0],
                'date' => $date[0],
                'hr' => $hr[0],
                'isms' => $isms[0],
                'product' => $product[0],
                'exploitation' => $exploitation[0]
            ],

        ],
    ];

我的问题是我想创建一个函数(PHP)以便在这个数组中添加一些行。我希望得到这样的结果:

        $result = [ 'data' =>
        [0 =>
            [
                'months' => $months[0],
                'years' => $years[0],
                'date' => $date[0],
                'hr' => $hr[0],
                'isms' => $isms[0],
                'product' => $product[0],
                'exploitation' => $exploitation[0]
            ],
            [
                'months' => $months[0],
                'years' => $years[0],
                'date' => $date[0],
                'hr' => $hr[0],
                'isms' => $isms[0],
                'product' => $product[0],
                'exploitation' => $exploitation[0]
            ]
        ]
    ];

但每当我尝试推动时,它会创建一个" 1 => ...."

我该怎么办?你能帮帮我吗?

2 个答案:

答案 0 :(得分:0)

您需要执行以下操作: -

 $result['data'][] = [
                'months' => $months[0],
                'years' => $years[0],
                'date' => $date[0],
                'hr' => $hr[0],
                'isms' => $isms[0],
                'product' => $product[0],
                'exploitation' => $exploitation[0]
            ];

输出: - https://eval.in/990308

答案 1 :(得分:0)

你的第一个数组应该是这样的 -

$result = [ 'data' =>
          [0 => 
              [0 =>
            [
                'months' => $months[0],
                'years' => $years[0],
                'date' => $date[0],
                'hr' => $hr[0],
                'isms' => $isms[0],
                'product' => $product[0],
                'exploitation' => $exploitation[0]
            ],
             ],
          ],
      ];

现在使用下面的代码将新行添加到数组中 -

$row = [
        'months' => $months[0],
        'years' => $years[0],
        'date' => $date[0],
        'hr' => $hr[0],
        'isms' => $isms[0],
        'product' => $product[0],
        'exploitation' => $exploitation[0]
            ];
$result['data'][0][] = $row;
print_r($result);