繁体   English   中英

PHP的foreach偶数和奇数,但反之亦然后打印2行

[英]php foreach even and odd but vice versa after printing 2 rows

在我的应用程序中,我必须循环两种尺寸的图像。 让我们称它们为大与小。.这些图像在下面的两列中。

large small
large small
large small

我现在通过这样做来按类生成赞美/小图像:

<?php $count = 0; ?>
<?php foreach ($posts as $post) : ?>
<div class=" <?=(++$count%2 ? "col-7 pr-10" : "col-5 pl-10");?> mt-15">
<?php endforeach; ?>

我现在想在这里做的就是产生这份清单。

large small
small large
large small
etc..

我可以通过哪种方式做到这一点? 我想我必须在每2个条目之后创建一种重置,并将eve设置为奇数,反之亦然。

通常,如果您需要AB; BA; AB; AB; BA; AB; 等连续循环,您可以这样做:

$row = 0;
foreach ($posts as $post) {
  if ($row%2) echo "A, B\n"; else echo "B, A\n";
  $row++;
}

这看起来很像您的代码…

相反,如果您真的是说您需要做

A
B
B
A

(模式基本上每4行重复一次),那么一种清晰合理的方法是:

$row = 0;
foreach ($posts as $post) {
  $temp = $row%4;
  if ($temp == 0 || $temp == 3 ) echo "A\n"; else echo "B\n";
  $row++;
}

显然,它可以变得更紧凑-但我通常发现六个月后“显式”更易于阅读-并且对性能的影响可以忽略不计。

尝试更换

<div class=" <?=(++$count%2 ? "col-7 pr-10" : "col-5 pl-10");?> mt-15">

<div class=" <?=($count%4 == 1 || ? $count%4 == 2)"col-7 pr-10" : "col-5 pl-10"; $count++;?> mt-15">
<?php $count = 0; $flag = 0;?>
<?php foreach ($posts as $post) : ?>
<?php $flag = $count%2 == 0 ? $flag + 1 : $flag;?>
<div class=" <?=(($count++ +$flag)%2 ? "col-7 pr-10" : "col-5 pl-10");?> mt-15">
<?php endforeach; ?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM