【问题标题】:Pattern in while loopwhile循环中的模式
【发布时间】:2010-12-09 20:52:38
【问题描述】:
<table>
while ($row = mysql_fetch_assoc($result)) {
<tr>
<td>
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
</td>
</tr>
}
</table>

如何为背景颜色制作图案?例如,灰色、蓝色、灰蓝色。

【问题讨论】:

  • 你的英语说不通。颜色不会要求您为它们制作图案。
  • 正确的表达方式是什么?
  • @Doug:建议,“如何制作具有交替背景颜色的图案?”
  • 这可能会引起人们的兴趣:stackoverflow.com/questions/399137/… 我相信这个问题已经被问过很多次了。

标签: php


【解决方案1】:

有多种方法可以做到这一点。这是一个。

<table>
<?php $i = 0; ?>
<?php while ($row = mysql_fetch_assoc($result)): ?>
<tr<?php echo (++$i & 1 == 1) ? ' class="odd"' : '' ?>>
<td>
<?php echo $row['test'] . " " . ' ($' . $row['test2'] . ") ?><br>
</td>
</tr>
<?php endwhile; ?>
</table>

我建议每隔一行给一个 CSS 类(我在这里称其为“奇数”),而不是奇数和偶数。然后你就这样做:

tr td { background: grey; }
tr.odd td { background: blue; }

在 CSS 中。

【讨论】:

    【解决方案2】:

    您需要一个状态变量之类的东西,用于存储最后一行是蓝色还是灰色。然后你打印出另一种颜色并更新下一次传递的状态变量。

    这是一个例子:

    <?php
    
    echo '<table>';
    
    $state = 1;
    while ($row = mysql_fetch_assoc($result)) {
        echo '<tr>';
        if( $state%2 == 0 )
            echo '<td style="background-color:grey;">';
        else
            echo '<td style="background-color:blue;">';
        echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
        echo '</td></tr>';
        $state++;
    }
    echo '</table>';
    
    ?>
    

    【讨论】:

      【解决方案3】:

      如果是 2 色图案,请使用变量在蓝色和灰色之间切换。如果超过 2 种颜色,请使用旋转计数器

      2 种颜色

      $blue = true;
      <table>
      while ($row = mysql_fetch_assoc($result)) {
      <tr>
      <td color="<?php echo $blue?'blue':'grey'; $blue ^= true; ?>">
      echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
      </td>
      </tr>
      }
      </table>
      

      2色以上,一般解决办法:

      $colourIndex = 0;
      $colours = ('blue', 'red', 'green');
      
      ...
      ...
      
      <td color="<?php echo $colours[$colourIndex]; $colourIndex = ($colourIndex+1)%length($colours); ?>">
      

      【讨论】:

      • $blue = !$blue 是一个不太聪明的方法。
      • ($counter + 1)%n 其中 n 是您拥有的颜色数量:P
      • 哈哈 Ollie,我使用 xor 是因为根据我的经验,它通常用于翻转一点,而 $blue = !$blue 看起来有点混乱......甚至哲学上,“蓝色不是蓝色” , "2b|!2b", "i.think() => i.am()"
      • 澄清:它是一个“旋转计数器”,因为它在计数到间隔的最后一个数字后“旋转”回到开始(间隔是具有开始和结束数字的数字序列)。
      • @Charles Ma:我通常告诉早期编程的学生,“=”不是等号。相反,它是“this is assignment with this”,以消除类 C 语言中“=”和“==”语义之间的任何混淆。
      【解决方案4】:

      您还可以使用InfiniteIterator 一次又一次地重复该序列。这就像“旋转计数器”一样,适用于任意数量的元素。

      $props = new InfiniteIterator(
        new ArrayIterator(array('a', 'b', 'c','d', 'e'))
      ); $props->rewind();
      
      $l = rand(10, 20); // or whatever
      for ($i=0; $i<$l; $i++) {
        $p = $props->current(); $props->next();
        echo 'class="', $p, '"... ';
      }
      

      【讨论】:

      • 真的吗?我发现这个解决方案比其他解决方案更容易阅读。并且更容易调整。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 2022-08-21
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 2016-11-27
      相关资源
      最近更新 更多