如何在foreach循环/ if语句中保留变量值

时间:2016-10-17 13:42:17

标签: php mysql

我正在尝试使用内部的IF语句运行foreach循环。我想保留$ nextupdate的值,这样我就可以将每个$ ex插入到特定的workoutID($ nextupdate)中。由于IF语句在第一次运行foreach循环时不会分开运行,因此在第一次循环后丢失了$ nextupdate的值。那么如何在第一次读取时保留$ nextupdate的当前值? 谢谢!

$check = 0;
$nextupdate = 0;

foreach($exer->results() as $ex){
    //echo $ex->Name."<br/>";
    //$curId = $ex->ExerciseID;
    //$sql2 = "SELECT * FROM exercises WHERE ExerciseID = ".$curId;
    //$details = DB::getInstance()->query($sql2);

    //print_r($details);
    //echo $details->results()[0]->StartReps;
    //$reps = $details->results()[0]->StartReps;
    //echo $details->results()[0]->StartSets;
    //echo $details->results()[0]->StartWeight;
    //echo "<br>";

    if($check = 0){
       $sql = "SELECT * FROM workoutexercises ORDER BY WorkoutID DESC LIMIT 1";
       $recentworkout = DB::getInstance()->query($sql);
       $updateworkout = $recentworkout->results()[0]->WorkoutID;
       $nextupdate = $updateworkout + 1;
       $check = 1;
       echo $nextupdate;
    }

    $sql = "INSERT INTO workoutexercises (ExerciseID, WorkoutID) VALUES (".$curId.",".$nextupdate.")";
    DB::getInstance()->query($sql);
}
?>

2 个答案:

答案 0 :(得分:1)

更改“if”中的支票,使用双等号:

  

if($check == 0){

$ nextupdate的值应该保留。这没什么不对。

答案 1 :(得分:0)

您使用single =而不是double ==来检查if语句中的条件。如果您将其更改为使用==,您的代码应该可以正常工作。

$check = 0;
$nextupdate = 0;

foreach($exer->results() as $ex){        
    if($check == 0){
       $sql = "SELECT * FROM workoutexercises ORDER BY WorkoutID DESC LIMIT 1";
       $recentworkout = DB::getInstance()->query($sql);
       $updateworkout = $recentworkout->results()[0]->WorkoutID;
       $nextupdate = $updateworkout + 1;
       $check = 1;
       echo $nextupdate;
    }

    $sql = "INSERT INTO workoutexercises (ExerciseID, WorkoutID) VALUES (".$curId.",".$nextupdate.")";
    DB::getInstance()->query($sql);
}
?>