On every third iteration in PHP(在 PHP 中的每三次迭代)
问题描述
我想在 PHP 循环的第三次迭代中输出一些特定的 HTML.这是我的代码:
I would like to output some specific HTML on the third iteration of a loop in PHP. Here is my code:
<?php foreach ($imgArray as $row): ?>
<div class="img_grid"><?= $row ?></div>
<?php endforeach; ?>
在此循环的第三次迭代中,不显示:
On the third iteration of this loop, Instead of displaying:
<div class="img_grid"><?= $row ?></div>
我想显示:
<div class="img_grid_3"><?= $row ?></div>
如果我的数组循环 8 次,我想以这个结束:
I would like to end up with this if my array looped 8 times:
<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>
谢谢
推荐答案
假设 $imgArray
是一个数组而不是关联数组(即它有数字索引),这就是你想要的:
Assuming $imgArray
is an array and not an associative array (i.e. it has numeric indices), this is what you want:
<?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; ?>
你可以像这样收紧一点:
You could tighten it up a bit like this:
<?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; ?>
甚至更多(有些人只会在 HTML 中使用三元条件内联),但收益递减法则最终会在可读性方面发挥作用.不过,希望这能给您提供正确的想法.
Or even more (some folks would just go with a ternary conditional inline in the HTML), but the law of diminishing returns kicks in eventually with regard to readability. Hopefully this gives you the right idea, though.
这篇关于在 PHP 中的每三次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 PHP 中的每三次迭代


基础教程推荐
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01