开发者

Change class for last two rows in a while loop

开发者 https://www.devze.com 2023-02-24 21:34 出处:网络
I 开发者_运维技巧have a while loop that displays result from a MySQL query. I know how to change the output for the last row or an odd row but how can I change the output for the last two results?

I 开发者_运维技巧have a while loop that displays result from a MySQL query. I know how to change the output for the last row or an odd row but how can I change the output for the last two results?

For example I have a list of results in a 2x2 matrix with border-bottom: 1px on each result but I would like to display the bottom two without the border?


If you can use css3, it´s easy (I´ll use a list for the example):

li:nth-last-child(-n+2)

selects the last two li's.

If you want to do it in php, you can count the number of results, add a counter in your loop and add a class to the last two items.


Yeah just do it like this:

$result = //execute your query
$num_rows = mysql_num_rows($result;
$num_rows_different = 2;

$loop_counter = 0;
while ($loop_counter < $num_rows) {
   if ($loop_counter < $num_rows - $num_rows_different) {
      // with border
   } else {
      // no border
   }
   $loop_counter++;
}

I wouldn't use the CSS3 method due to its poor support...


I like the CSS way, but you'll need to know the total number of items you're listing. Then you can use a simple condition to check for that.

$total_items = [count of items];
$cnt = 0;
while($fetch as $row) {
    ...
    if(++$cnt > ($total_items - 2)) {
        // list with no border
    } else {
        // list with border
    }
}
0

精彩评论

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

关注公众号