开发者

PHP Colour Every Box in the Middle

I have a list of boxes on my website:

box1    box2    box3
box4    box5    box6
box7    box8    box9

Does anybody have a suggestion how to mark every box in th开发者_运维问答e middle of the list (box2, box5, box8)?

Thanks for your help!

Here's my foreach loop:

<?php foreach($usersResult as $user) { ?>
    <div class="box">
        // other stuff here
    </div>
<?php } ?>


<?php $i=-1; foreach($usersResult as $user) { ?>
    <div class="box<?php echo ($i % 3 == 0 ? ' middle' : '') ?>">
        // other stuff here
    </div>
<?php $i++; } ?>

Explanation: % (modulus operator) will return the remainder of a division. So if you do $i % 3, it will be 0 whenever $i is dividable by 3 (without remainder). I added $i into your loop, and I start it from -1, because we don't need every third element, but every third element starting from the second (in a 0 based world, the first).

I also used the ternary operator (condition ? value_if_true : value_if_false).


Like so:

$i = 0;
foreach($boxes as $box){
    if((($i+2) % 3) === 1){
        //box2, box5, box8
    }
    else{
       //other boxes
    }
    $i++;
}


You should go with % and a for loop, something like this (not tested):

for( $i = 0; $i < 10; $i++ ) {
    if( (($i+1)%3) == 0 ) echo 'class="colored"';
}


Even slicker but lengthy - non Gofl example if you use arrays.

$boxes = array(1,2,3,4,5,6,7,8,9);

foreach($boxes as $key => $box){
    echo (($key+2)%3==0) ? "<b>" : "";
    echo "(".$key . ' -> ' . $box . ") ";
    echo (($key+1)%3==0) ? "<br/>" : "";
    echo (($key+2)%3==0) ? "</b>" : "";
}

Output:

(0 -> 1) (1 -> 2) (2 -> 3)

(3 -> 4) (4 -> 5) (5 -> 6)

(6 -> 7) (7 -> 8) (8 -> 9)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜