首页 > 解决方案 > 如何在循环中仅显示一次 div 并在仅运行一次的 div 内显示下一个 div

问题描述

我尝试在 google 和 SO 上找到解决方案,但我没有找到解决方案。

我有一个类似的代码。

$index = 0;
while (some condition here) { 
         if ($index < 4) {?>
            <div class="first4">
              <p>Some text here</p>
            </div>
    <?php }
        else{
            $check=0;
            if ($check==0){?>
              <div class="displayOnceInwhile">
            <?php $check=1; }?>
            <div class="InsideaboveClass"></div>

    <?php } 

$index++;}?>

我对上述代码所做的是,如果$index小于 4,则内部文本将显示 else$check将仅在循环中运行一次,但它不起作用。另外,请注意这里我混淆了我应该在哪里关闭displayOnceInwhile关闭</div>

预期结果

<!--first 4 will display-->
    <div class="first4"><p>Some text here</p></div>
     <div class="first4"><p>Some text here</p></div>
     <div class="first4"><p>Some text here</p></div>
     <div class="first4"><p>Some text here</p></div>
<!--Set will display like this-->
     <div class="displayOnceInwhile">
      <div class="InsideaboveClass"></div>
    </div>

标签: phphtmlloops

解决方案


希望这就是你想要做的。

<?php
$check = 0;
$index = 0;
while (some condition here) { 
    if ($index < 4) {
        echo '<div class="first4"><p>Some text here</p></div>';
    } else {
        if ($check==0){
            echo '<div class="displayOnceInwhile">';
            $check=1;
        }
        echo '<div class="InsideaboveClass"></div>';
    }
    $index++;
}
echo '</div>';
?>

推荐阅读