dql7588 2018-07-16 01:23
浏览 174
已采纳

PHP foreach循环记住最后一个循环变量

Good morning/afternoon Y'all,

I am running into a weird issue where it seems that one of my foreach loops is remembering variables from its last loop.

Here is the loop in question:

foreach($result as $obj) {
    $S_MatterNum = $obj['matter_num'];
    $S_SurveyName = $obj['longname'];
    $D_DateSubmit = new datetime($obj['date_submit']);
    $D_DateComp = new datetime ($obj['date_complete']);
    echo "<tr id=" . $S_MatterNum . ">";
    echo '<td>' . $S_MatterNum . '</td>';
    echo '<td>' . $S_SurveyName . '</td>';
    echo '<td>' . $D_DateSubmit->format('d/m/Y') . ' & '. $D_DateComp->format('d/m/Y') .'</td>';
    if (!isset($D_DateComp)){
        $D_DateComp = 'Not Completed Yet';
        echo '<td>' . $D_DateComp . '</td>';
        echo '<td></td>';
    } else {
        echo '<td>' . $D_DateComp->format('d/m/Y'). '</td>';
        echo '<td><button onclick="pullsurvey('.$S_MatterNum.')">Pull</button></td>';
    }
    echo "</tr>";
}

The issue I am having is with the $D_DateComp variable. The loop gets its information from the following:

$SQL = "SELECT * FROM survey_list INNER JOIN survey_names ON survey_list.survey_name = survey_names.shortname";
$result = mysqli_query($con,$SQL);
if ($result === false) {
        echo("Error: " . $SQL . "<br>" . $con->error);
}
if (mysqli_num_rows($result) == 0) {
    $result = mysqli_fetch_all($result,MYSQLI_ASSOC);
}

Now if the date_complete column in the table is NULL (the survey hasn't been completed yet) then $D_DateComp is being set to the last non-NULL occurrence instead of being set to NULL, so it could be being set to the value of $D_DateComp from 5 loops ago.

Is this caused by the way I pull the information out of the database, or is it caused by the way I process the info once it is out?

If the above is a little bit too cryptic I can try and explain all the separate parts and provide screenshots.

  • 写回答

1条回答 默认 最新

  • drui0508 2018-07-16 01:31
    关注

    You're instantiating a DateTime instance without any sort of condition:

    $D_DateComp = new datetime ($obj['date_complete']);
    

    Then you check if this variable is set:

    if (!isset($D_DateComp)){
    

    $D_DateComp will always be set, it will be a DateTime instance. Your problem isn't that the variable is sharing the value of the previous iteration, the problem is your condition doesn't match your expectations.

    Maybe you should be checking if $obj['date_complete'] is null?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波