如何在 PHP 计数器的循环中定位块 1、3、5 等
How to target block 1, 3, 5 etc. in a loop with PHP counter
我正在尝试将 div class "row" 添加到我的第 1、3、5 个区块等
我已经掌握了基础知识,但它一直以块 2、4、6 等为目标。我已经苦苦思索了一个小时,因为我认为它真的很简单,但对 none 知之甚少 PHP 我只是没弄对。
这是我的:
<?php $counter = 1; ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
if ($counter % 2 == 0) {
echo "<div class=\"row\">ROW";
}
?>
<p>Title #<?php print "$counter"; ?></p>
<?php
if ($counter % 2 == 0) {
echo "</div>";
}
?>
<?php $counter ++; ?>
谁能给我指出正确的方向?提前致谢!
使用$counter % 2 == 1
定位奇数
它定位偶数行的原因是因为你在做
$counter % 2 == 0
您需要了解 %
的作用。 %
是一个 Modulus Operator,它将得到 $x 除以 $y 的余数,如 link.
中所述
所以如果你想得到奇数,你必须做
$counter % 2 != 0
或
$counter % 2 == 1
我正在尝试将 div class "row" 添加到我的第 1、3、5 个区块等
我已经掌握了基础知识,但它一直以块 2、4、6 等为目标。我已经苦苦思索了一个小时,因为我认为它真的很简单,但对 none 知之甚少 PHP 我只是没弄对。
这是我的:
<?php $counter = 1; ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
if ($counter % 2 == 0) {
echo "<div class=\"row\">ROW";
}
?>
<p>Title #<?php print "$counter"; ?></p>
<?php
if ($counter % 2 == 0) {
echo "</div>";
}
?>
<?php $counter ++; ?>
谁能给我指出正确的方向?提前致谢!
使用$counter % 2 == 1
定位奇数
它定位偶数行的原因是因为你在做
$counter % 2 == 0
您需要了解 %
的作用。 %
是一个 Modulus Operator,它将得到 $x 除以 $y 的余数,如 link.
所以如果你想得到奇数,你必须做
$counter % 2 != 0
或
$counter % 2 == 1