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?

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

报告相同问题?

悬赏问题

  • ¥20 matlab中的双层数值积分
  • ¥15 Delphi image图片缩放问题
  • ¥30 gradle环境下javafx项目如何使用druid连接池
  • ¥15 服务器打印水晶报表问题
  • ¥15 初学者用plt报错,求解答
  • ¥18 深度学习tensorflow1,ssdv1,coco数据集训练一个模型
  • ¥100 关于注册表摄像头和麦克风的问题
  • ¥30 代码本地运行正常,但是TOMCAT部署时闪退
  • ¥15 关于#python#的问题
  • ¥15 主机可以ping通路由器但是连不上网怎么办