在PHP中的每三次迭代

Kor*_*ory 1 php iteration loops

我想在PHP的循环的第三次迭代中输出一些特定的HTML.这是我的代码:

<?php foreach ($imgArray as $row): ?>
   <div class="img_grid"><?= $row ?></div>
<?php endforeach; ?>
Run Code Online (Sandbox Code Playgroud)

在此循环的第三次迭代中,而不是显示:

<div class="img_grid"><?= $row ?></div>
Run Code Online (Sandbox Code Playgroud)

我想展示:

<div class="img_grid_3"><?= $row ?></div>
Run Code Online (Sandbox Code Playgroud)

如果我的数组循环8次,我想结束这个:

   <div class="img_grid">[some html]</div>
   <div class="img_grid">[some html]</div>
   <div class="img_grid_3">[some html]</div>
   <div class="img_grid">[some html]</div>
   <div class="img_grid">[some html]</div>
   <div class="img_grid_3">[some html]</div>
   <div class="img_grid">[some html]</div>
   <div class="img_grid">[some html]</div>
Run Code Online (Sandbox Code Playgroud)

谢谢

Jor*_*ing 12

假设$imgArray是一个数组而不是一个关联数组(即它有数字索引),这就是你想要的:

<?php foreach($imgArray as $idx => $row): ?>
  <?php if($idx % 3 == 2): ?>
    <div class="img_grid_3"><?php echo $row; ?></div>
  <?php else: ?>
    <div class="img_grid"><?php echo $row; ?></div>
  <?php endif; ?>
<?php endforeach; ?>
Run Code Online (Sandbox Code Playgroud)

你可以把它收紧一点:

<?php foreach($imgArray as $idx => $row):
        if($idx % 3 == 2) {
          $css_class = 'img_grid_3';
        } else {
          $css_class = 'img_grid';
        }
?>
  <div class="<?php echo $css_class; ?>"><?php echo $row; ?></div>
<?php endforeach; ?>
Run Code Online (Sandbox Code Playgroud)

甚至更多(有些人会在HTML中使用三元条件内联),但收益递减规律最终会在可读性方面发挥作用.但是,希望这能为您提供正确的想法.

  • 这是标准的PHP语法.你可以消除一些<?php标签,但它并没有真正使它更具可读性.这就是为什么MVC和模板语言是我们的朋友. (4认同)