2011-01-28 100 views
1

即时通讯设法从数据库中获取数据并将其列在<li>列表中。即时通讯试图找出每个第三个列表项并给它一个不同的李类?这是我的代码确定php while while循环中的每个第三项?

<?php 
while ($row = mysql_fetch_array($getupdates)){ 
?> 
<li id="update" class="group"> 
    blah blah blah 
</li> 
<?php } ?> 

所以基本上每隔3个项目,我想给它一个不同的立类

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

添加支持作为一般的经验法则,从来没有使用shorttags(<或<=而不是<?PHP的。他们弃用,一些服务器 – phihag 2011-01-28 23:01:27

+0

OOOOH,FizzBu​​zz! – webbiedave 2011-01-28 23:42:27

回答

6

有在while循环的计数器。我们称之为$i。在你的循环,补充一点:

$i++; 
if ($i % 3 == 0) { 
    //do something you'd do for the third item 
} 
else { //default behavior } 
0
<?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>'; 
} 
1

使用计数器,然后只需检查计数器的模3为0或不以确定它是否是一个第三排。

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

Modulus operator是要走的路。

但是,您也可以使用CSS3属性来实现相同的效果,而不使用PHP。

2

使用CSS3伪类属性选择器,您可以更轻松地做到这一点。事情是这样的:?

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

如果你担心IE支持CSS3的属性,你可以很容易地用填充工具像http://selectivizr.com/