21

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.

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.

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!

2 Answers 2

35

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


You want to use array_push to append to an array. This way you will get an array of $playerdata arrays.

array_push($allplayerdata, $playerdata);

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

$allplayerdata[] = $playerdata;

Sign up to request clarification or add additional context in comments.

Comments

9

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

$allplayerdata[] = $playerdata;

1 Comment

I think you should clarify that merge replaces the elements with the same index. It would be more helpful that way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.