循环的每第1次和第3次迭代

时间:2015-11-20 16:12:27

标签: php loops if-statement operators modulus

我正在对旧的客户端WP站点(因此是960.gs网格)进行更新,并且有一个循环来输出丢失的新闻项目。

我想要实现的目标(使用if语句)是将.alpha类设置为第1项以及数字4,7,10,13 ...等我也在尝试将.omega应用于3,6,9,12等......

这是带有模运算符的if语句: <?php if ($count % 1 == 0) : ?>alpha <?php endif; ?>grid_4<?php if ($count % 3 == 0) : ?> omega<?php endif; ?>

但这给了我以下内容:

<div class="feed">

    <div class="alpha grid_4">

        <p>In condimentum facilisis porta. Sed nec diam eu diam mattis viverra. Nulla fringilla, orci ac euismod semper, magna diam porttitor mauris, quis sollicitudin.</p>

    </div>

    <div class="alpha grid_4">

        <p>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin vel ante a orci tempus eleifend ut et magna. Lorem ipsum dolor sit amet, consectetur adipiscing […]</p>

    </div>  

    <div class="alpha grid_4 omega">

        <p>Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere. Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue […]</p>

    </div>

    <div class="alpha grid_4">

        <p>Duis aliquet egestas purus in blandit. Curabitur vulputate, ligula lacinia scelerisque tempor, lacus lacus ornare ante, ac egestas est urna sit amet arcu. Class aptent taciti sociosqu ad litora torquent […]</p>

    </div>

    <div class="alpha grid_4">

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus luctus urna sed urna ultricies ac tempor dui sagittis. In condimentum facilisis porta. Sed nec diam eu diam mattis viverra. Nulla […]</p>

    </div>

    <div class="alpha grid_4 omega">

        <p>Curabitur vulputate, ligula lacinia scelerisque tempor, lacus lacus ornare ante, ac egestas est urna sit amet arcu. Class aptent taciti sociosqu ad litora torquent per conubia. Curab itur vulputate, ligula […]</p>

    </div>

    <div class="alpha grid_4">

        <p>Mauris iaculis porttitor posuere. Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum […]</p>

    </div>

</div>

如您所见,.omega似乎工作正常,但.alpha正在应用于每个元素。

2 个答案:

答案 0 :(得分:2)

你除以1,所以alpha应用于任何地方。

更改if语句如下:

<?php if ($count % 3 == 1) : ?>alpha <?php endif; ?>grid_4<?php if ($count % 3 == 0) : ?> omega<?php endif; ?>

答案 1 :(得分:0)

解决方案可能是:

<?php if ($count == 0 ) : ?>alpha <?php endif; ?>grid_4<?php if ($count % 3 == 0) : ?> omega<?php endif; ?>

简而言之,使用1操作数的模数(%)操作将在任何数字上返回0,因为任何整数都可以除以1(结果是数字本身,因此模数为零)。