Reputation: 115
I have an array with names, goal differences and so on for football teams that I want to put in a table, but during the foreach the last key in the array is changed somehow.
Last two keys before foreach
[18] => Array
(
[team_code] => 4
[team_name] => Newcastle
[points] => 6
[goals_for] => 12
[goals_against] => 22
[goal_difference] => -10
)
[19] => Array
(
[team_code] => 7
[team_name] => Aston Villa
[points] => 4
[goals_for] => 9
[goals_against] => 17
[goal_difference] => -8
)
)
After foreach
[18] => Array
(
[team_code] => 4
[team_name] => Newcastle
[points] => 6
[goals_for] => 12
[goals_against] => 22
[goal_difference] => -10
)
[19] => Array
(
[team_code] => 4
[team_name] => Newcastle
[points] => 6
[goals_for] => 12
[goals_against] => 22
[goal_difference] => -10
)
)
My foreach looks like this
foreach ($teams as $team) {
$team_code = $team['team_code'];
$team_name = $team['team_name'];
$points = $team['points'];
$goals_for = $team['goals_for'];
$goals_against = $team['goals_against'];
$goal_difference = $team['goal_difference'];
if ($update_query = $conn->query("UPDATE teams SET points = $points, goals_for = $goals_for, goals_against = $goals_against, goal_difference = $goal_difference WHERE team_code = $team_code")) {
echo 'Updated '.$team_name.'<br>';
} else {
$update_query->error;
}
}
Why is the last key changed? It happens before the query is run, because the row doesn't get updated. All the others update as they should.
Upvotes: 1
Views: 26
Reputation: 36
I don't think that there's anything wrong with your php script. I would take a look at how the array is build before it get to the foreach loop. How is the form for which you enter the data set up. If you are entering multiple teams at once, how are you differentiating the elements
Upvotes: 0
Reputation: 115
Thanks to VolkerK I managed to solve it.
I have another foreach with a reference to &$team
before the foreach, and putting unset($team)
between the two foreachs solved the problem.
Upvotes: 1