使用foreach更新数据库正在更新之前更改数组

时间:2015-10-28 13:29:13

标签: php arrays foreach

我有一个数组,其名称,目标差异等等,我希望将橄榄球队放在一张桌子中,但在foreach期间,数组中的最后一个键会以某种方式改变。

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
        )

)

在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
        )

)

我的foreach看起来像这样

  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;
    }
  }

为什么最后一把钥匙改变了?它在运行查询之前发生,因为该行不会更新。所有其他人都应该更新。

2 个答案:

答案 0 :(得分:1)

感谢VolkerK,我设法解决了这个问题。

我有另一个foreach在foreach之前引用了&$team,并且在unset($team)之间放置了两个foreach解决了这个问题。

答案 1 :(得分:0)

我不认为您的PHP脚本有任何问题。我会先看看数组在进入foreach循环之前是如何构建的。您输入数据的表单是如何设置的。如果您一次进入多个团队,您如何区分元素