开发者

Help needed improving a foreach loop

I have this l开发者_运维知识库ogic written that loops out an array into <li>

and gives #1 and every 5th a class of "alpha".

$count = 0;

        foreach($gallery->data as $row){

            if ($count==0 || $count%4==0) {
                echo '<li class="alpha"></li>'.PHP_EOL;
            } else {
                echo '<li></li>'.PHP_EOL;
            }

            $count++;
        }

I need to add to this and get the code adding a class of "omega" to every 4th <li>


You do realize that as you describe it, there will be some overlap right? (example - item 30 is both a '5th' and a '6th') Brian gave you an answer for exactly what you described, but I'm not sure if its what you want. You want ALPHA, x, x, x, OMEGA, ALPHA, x, x, x, OMEGA, ALPHA.....

You seem to want Alpha on the 5*k + 1, and Omega on 5*k

conditions:
alpha - ($count + 1) % 5 == 1
omega - ($count + 1) % 5 == 0

I think grouping in the addition makes this easier to understand, since you're count starts at 0 but you seem to be thinking in terms of beginning at 1. If you don't like that, lose the addition and change the equivalences to 0 and 4, respectively - $count % 5 == 0 and $count % 5 == 4

i know this is better suited for a comment under the last answer, but I don't see how. Am i not allowed until my reputation is higher or am i just missing something?>


right now as it stands your code adds the "alpha" class to every fourth item beginning with the first, not every fifth. In other words, items 1, 5, 9, 13, etc. will have a class of "alpha" since your counter begins at 0.

I assume that you want to add the "omega" class then to items 4, 8, 12, etc. Here's what you need to do that:

$count = 0;

    foreach($gallery->data as $row){ 

        if ($count%4==0) { 
            echo '<li class="alpha"></li>'.PHP_EOL; 
        }
        else if ($count%4==3) {
            echo '<li class="omega"></li>'.PHP_EOL;
        } 
        else { 
            echo '<li></li>'.PHP_EOL; 
        } 

        $count++; 
    } 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜