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?

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

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备