Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

php - Help needed improving a foreach loop

I have this logic 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>

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...