开发者

determining each third item in a php while loop?

im trying to get data from the database and list them in a <li> list. im trying to find out each third list item and give it a diffrent li class? this is my code

<?php
while ($row = mysql_fetch_array($getupdates)){
?>
<li id="update" class="gro开发者_JS百科up">
   blah blah blah
</li>
<?php } ?>

so basically for every third item i want to give it a different li class

<li id="update" class="group third">


Have a counter in your while loop. Let's call it $i. In your loop, add this:

$i++;
if ($i % 3 == 0) {
   //do something you'd do for the third item
}
else { //default behavior }


You could do this a lot easier using CSS3 pseudo-class attribute selectors. Something like this:

li:nth-child(3) {
  font-weight: bold;
}

If you're worried about IE support of CSS3 attributes, you can easily add support with a polyfill like http://selectivizr.com/


Use a counter, and then just check if modulo 3 of the counter is 0 or not to determine if it's a third row.

<?php
$rowCount = 0;
while ($row = mysql_fetch_array($getupdates))
{
    $useDiffClass = (($rowCount++ % 3) == 0);    
    ?>
    <li id="update" class="group <?=($useDiffClass ? "third" : "");?>">
        blah blah blah
    <li>
    <?
}
?>


<?php
$i = 0;
while (($row = mysql_fetch_array($getupdates)) !== false){
   echo '<li id="update" class="group';
   if ($i++ % 3 == 2) echo ' third';
   echo '">blah blah blah</li>';
}


Modulus operator is the way to go.

But you may also use CSS3 attributes to achieve the same effect without using PHP.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜