php 将数组添加到循环内的多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6892148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:33:46  来源:igfitidea点击:

Adding arrays to multi-dimensional array within loop

phparrayscodeignitermultidimensional-array

提问by Leopold Stotch

I am attempting to generate a multi-dimensional array with each sub array representing a row I want to insert into my DB. The reason for this is so I can use CodeIgniters batch_insert function to add each row to the DB.

我正在尝试生成一个多维数组,每个子数组代表我想插入到我的数据库中的一行。这样做的原因是我可以使用 CodeIgniters batch_insert 函数将每一行添加到数据库中。

I am attempting to create each sub array within a loop and insert it into a multidimensional array. Google suggested using array_merge, but after using 'print_r' on the multidimensional array with the code below, only the last sub-array is being displayed.

我试图在循环中创建每个子数组并将其插入到多维数组中。Google 建议使用 array_merge,但是在使用下面的代码在多维数组上使用 'print_r' 后,只显示最后一个子数组。

Here is my code:

这是我的代码:

$allplayerdata = array(); //M-D container array
for ($i = 1; $i <= 11; $i++)
{
    $playerdata = array(
                        'player_id' => $this->input->post('player' . $i),
                        'goals' => $this->input->post('playergoals' . $i),
                        'player_num' => $i,
                        'fixture_id' => $this->input->post('fixture_id')
                    );

    //Merge each player row into same array to allow for batch insert
    $allplayerdata = array_merge($allplayerdata, $playerdata);
}
print_r($allplayerdata);

Can anyone spot where I'm going wrong? Help is appreciated!

谁能发现我哪里出错了?帮助表示赞赏!

回答by Mark Biesheuvel

This is because array_mergeis not the right operation for this situation. Since all the $playerdataarrays have the same keys, the values are overridden.

这是因为array_merge对于这种情况不是正确的操作。由于所有$playerdata数组都具有相同的键,因此会覆盖这些值。



You want to use array_pushto append to an array. This way you will get an array of $playerdataarrays.

您想用于array_push附加到数组。这样你就会得到一个数组$playerdata数组。

array_push($allplayerdata, $playerdata);

Which is equivalent to adding an element with the square bracket syntax

相当于用方括号语法添加元素

$allplayerdata[] = $playerdata;


回答by JK.

This will add the second array to the first array: A mergeis something different.

这会将第二个数组添加到第一个数组:合并是不同的。

$allplayerdata[] = $playerdata;