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 c#里的静态变量为什么是错误的?
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术
  • ¥15 DockerSwarm跨节点无法访问问题
  • ¥15 使用dify通过OpenAI 的API keys添加OpenAI模型时报了“Connection Error”错误