doujuncuo9339 2014-10-20 07:59
浏览 38
已采纳

试图找出为什么这个PHP while循环实际上工作

This question is based on a reply I got from a question I submitted earlier:

Print new <div> on id iteration change inside php while loop from MySQL result

It's not really a problem, but I'm trying to understand what's going on.

I can't figure out why this loop does not add </div> to the variable $html at the very first iteration when $previous is equal to null

$previous = null;

while ($result = $stmt->fetch()) {

    if ($_company_id !== $previous) {
        if($previous !== null) {
            $html .='</div>';
        }
        $html .= '<div id="company-' . $_company_id . '" class="tab-pane fade">';
    }

    $previous = $_company_id;

}

if($previous != null) {
    $html.='</div>';
}

The output is exactly as I want it:

<div id="company-1" class="tab-pane fade"></div>
<div id="company-2" class="tab-pane fade"></div>

But I just can't understand why. Can anyone please explain this to me?

  • 写回答

1条回答 默认 最新

  • dtvnbe1428 2014-10-20 08:05
    关注

    Actually because they check IF IS NOT. Take a closer look at

     if($previous !== null) {
       $html .='</div>';
     }
    

    So it gets skipped on the first go through. On Every other Turn it has a value and the condition is true. hence executing the code.

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

报告相同问题?

悬赏问题

  • ¥30 数字信号处理实验报告
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程