在PHP的while循环中偶数和奇数之间交替 [英] Alternating between even and odd in a while loop in PHP

查看:26
本文介绍了在PHP的while循环中偶数和奇数之间交替的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在编写几行代码,但似乎无法让它工作.基本上我想通过 while 循环在偶数和奇数表样式之间交替.我做错了什么?

I have been working on couple of lines of code but I can't seem to get it to work. Basically I want to alternate between even and odd table-styles via a while loop. What am I doing wrong?

似乎每次都只循环遍历 if().

Seems as though it only loops through the if() everytime.

谢谢!

<?php
    include 'connect.php';
    echo "<table id='hor-zebra'>";
    $i = 0;
    while($row = mysql_fetch_array($result))
    {
       if(i%2 == 0)
       {
          echo "<tr class='even'>";
          echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
          echo "</tr>";
       }
       
       else
       {
          echo "<tr>";
          echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
          echo "</tr>";
       }
       $i++;
    }
    echo "</table>";

    mysql_close($con);

  ?>

推荐答案

您的 if 条件中存在拼写错误.应该是:

You have a typo in your if condition. It should be:

   if($i%2 == 0)

您还可以通过将类名分配给 if 和 else 块中的变量来节省几次按键操作:

You can also save a few keystrokes by just assigning the class name to a variable in the if and else blocks:

   if($i%2 == 0)
   {
      $class = 'even';
   }
   else
   {
      $class = 'odd';
   }

   echo "<tr class='$class'>";
   echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
   echo "</tr>";

这篇关于在PHP的while循环中偶数和奇数之间交替的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆