【问题标题】:How to display div only once in the loop and next div display inside div which run only once如何在循环中只显示一次 div 并在 div 中显示下一个 div 只运行一次
【发布时间】:2020-03-05 17:36:51
【问题描述】:

我尝试在 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,则内部文本将显示,否则 $check 将在循环中仅运行一次,但它不起作用。另外,请注意这里我很困惑我应该在哪里关闭 displayOnceInwhile 关闭 &lt;/div&gt;

预期结果

<!--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>

【问题讨论】:

  • 在你检查之前你有$check=0;在线 - 所以它总是0,试着把它放在你的while之前。
  • @NigelRen,让我试试这个
  • @NigelRen,再想一想。我还没有关闭这个div。我应该在哪里关闭这个
    的 div?
  • 你能用这个添加预期的结果吗?
  • @Prifulnath,更新了问题的结果。

标签: php html loops


【解决方案1】:

希望这就是你想要做的。

<?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>';
?>

【讨论】:

  • 给我一些时间检查
【解决方案2】:

您可以使用以下内容来构建您的 HTML

<?php
$first = '<div class="first4" ><p > Some text here </p ></div >';
$firstOpen = '<div class="first4" ><p > Some text here </p >';
$firstClose = '</div>';
$once = '<div class="displayOnceInwhile"><div class="InsideaboveClass"></div>';

$index = 0;
while ($index < 3) {
    echo $first;
    $index++;
}
echo $firstOpen;
echo $once;
echo $firstClose;

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签