开发者

Alternating Designs For Loop Results

开发者 https://www.devze.com 2022-12-15 06:06 出处:网络
I am looking to create alternating designs for the con开发者_如何学运维tent of each post returned in my loop. In short I want the first post to display left align, next right align, and so on. I have

I am looking to create alternating designs for the con开发者_如何学运维tent of each post returned in my loop. In short I want the first post to display left align, next right align, and so on. I have not been able to find a way to do this. Any ideas?


Try something like this:

$count = 0;
foreach ($posts as $post) {
    echo "<div class=\"" . (++$count % 2 ? 'left' : 'right') . "\">"
        . $post['postText'] // or whatever the crazy wordpress thing is
        . "</div>"
    ;
}


You could loop through the results and then check if an incremented counter is even or odd and display left or right depending on that.


Have a look at the modulo operator '%'

0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
...
100 % 2 = 0
101 % 2 = 1

You can have a repeating pattern of as many as you like:

0 % 4 = 0
1 % 4 = 1
2 % 4 = 2
3 % 4 = 3
4 % 4 = 0
5 % 4 = 1
....

C.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号