Welcome to WebmasterWorld Guest from 54.198.222.129

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

multiple Nth loop iterations

     
1:41 am on Jan 17, 2013 (gmt 0)

10+ Year Member



I'm trying to output data from mysql using a while loop into a framework. I need to have classes assigned to certain Nth iterations to maintain the layout provided by the framework.

The first iteration and every fourth one after have one class (alpha, ie, first div in row).
The fourth div and every fourth after that have another (omega, ie, last div in row). So I need something roughly like this:


<div class="alpha"> <div> <div> <div class="omega">
<div class="alpha"> <div> <div> <div class="omega">
<div class="alpha"> <div> <div> <div class="omega">
.. and so on


I've been trying to figure it out using the modulus operator but can't seem to wrap my head around how to target multiple Nth iterations. Can someone lend a guy a hand? Is there a better way?

Here's my gnarley existing code


$x = 0;
while ($row = mysql_fetch_assoc($result)){
if ($x % 1 == 0 || 5 == 0) {
echo '<div class="alpha">';
} elseif ($x == 4) {
echo '<div class="omega">';
} else {
echo '<div>';
}
}


Thanks in advance.

gen
10:56 pm on Jan 20, 2013 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Modulus may not be your best option in this case because what if you needed a class on the second div? 2 and 4 are both going to be equally divisible on certain integers in your set. I think you may be better served using a counter:
<pre> 
<?php
// set your alpha/omega here:
$alpha = 1;
$omega = 4;
$reset = 5; // how many total divs before next set?
$count = 0; // initialize our counter
for ($i = 1; $i <= 28; $i++) {
if (++$count == $reset) { // increase and compare
$count = 1; // reset if necessary
}
if ($count == $alpha) {
print '&#60;div class="alpha"&#62; ';
} else if ($count == $omega) {
print '&#60;div class="omega"&#62;'."\n";
} else {
print '&#60;div&#62; ';
}
}
exit;
?>
<pre>

outputs something like this:
<div class="alpha"> <div> <div> <div class="omega"> 
<div class="alpha"> <div> <div> <div class="omega">
<div class="alpha"> <div> <div> <div class="omega">
<div class="alpha"> <div> <div> <div class="omega">
<div class="alpha"> <div> <div> <div class="omega">
<div class="alpha"> <div> <div> <div class="omega">
<div class="alpha"> <div> <div> <div class="omega">
 

Featured Threads

Hot Threads This Week

Hot Threads This Month