PHP 第 n 次迭代


PHP nth iteration

所以我正在尝试使用 PHP 生成一些具有第 n 个循环需要打开或关闭div 元素的标准的内容。 所以我的目标是在页面和第 9 个元素上显示 8 个元素,我想关闭第 8 个元素的div,如果还有更多图像,请为第 9 个元素打开一个新元素。 这是我的代码。

$images; // object
$i = 1;
echo '<div class="outer-container">';
while ( $images->have_images() ) {
     if ( $i === 1 ) {
          echo '<div class="inner-container">';
     }
     echo 'content here';
     if ( $i === 8 || $images->total === $images->current + 1 ) {
          echo '</div><!--.inner-container-->';
     }
     $i++;
}
echo '</div><!--.outer-container-->';

最终结果应如下所示:

<div class="outer-container">
<div class="inner-container">
    content here
    content here
    content here
    content here
    content here
    content here
    content here
    content here
</div><!--.inner-container-->
<div class="inner-container">
    content here
    content here
    content here
</div><!--.inner-container-->
</div><!--.outer-container-->

搜索了一下,得出的结论是我可能必须使用模量,但我不确定如何将其合并到我的代码中。

谢谢你的关注。

if ( $i % 8 == 0) {
      echo '</div><!--.container--><div class="container">';
}

模组运算符返回余数。您可以简单地说明$i % 8$i % 8 == 0$i % 8 === 0 as john stated

但是您还需要在条件中打开下一个div,具体取决于您的结构方式。举个例子:

<div class="outer-container">
    <div class="inner-container">
        <?php
        $images; // object
        $i = 1;
        while ( $images->have_images() ) {
             echo 'content here';
             //print_r($i % 8);
             if ( $i % 8 == 0 && $images->total > 8) {
                  echo '</div><!--.inner-container--><div class="inner-container">';
             }
             $i++;
        }
        ?>
    </div>
</div>

添加了条件,以防您的图像总数恰好为 8,它不会创建一个流氓空div。

我试图理解你的评论。你是说你有一个外部容器,然后是一个内部容器,在这个内部容器中,你想要你在问题中定义的循环,其中每组 8 个都包含在一个 containerdiv 中?

我在循环中添加了一个打印 r,您可以取消注释以验证$i正在执行您想要的操作。通过此代码以及$i从 1 开始的事实,您不应该过早地体验结束div 条件。

模数确实是你正在寻找的:

if ( $i % 8 === 0 ) {
    echo '</div><!--.container-->';
}

你忘了打开一个新的div

修改以下代码:

if ( $i === 8 || $images->total === $images->current + 1 ) {
    echo '</div><!--.container-->';
    echo '<div class="container">'; //ADD THIS LINE!!!
}

退出while后添加结束</div>标签