【问题标题】:How to manipulate first 3 entries in array如何操作数组中的前 3 个条目
【发布时间】:2009-10-01 15:34:16
【问题描述】:

我目前正在从事一个项目,我正在使用其中提取数据 而($r = mysql_fetch_array($the_data))

我想制作第一个,比如 3-4 结果不同的背景颜色,然后将其余部分保留为已经设置的样式,我确信这里有一些简单的选项,但我只是不知道在哪里看真的.. .

希望你能帮忙,谢谢!

【问题讨论】:

    标签: php mysql arrays


    【解决方案1】:

    您是否正在寻找类似的东西:

    #specialResult {background-color: #fff; }
    #normalResult {background-color: #000; }
    

    因此,当您循环遍历您的 while 语句时,您需要跟踪您所处的结果编号:

    $i = 0;
    while (...)
    {
        if ($i < 4) echo "<div class='specialResult'>";
        else echo "<div class='normalResult'>"; 
    
        .... rest of your code
    
        $i++;
    }
    

    对于更短的代码,您可以这样做:

    $i = 0;
    while (...)
    {
        ?><div class='<?php echo ($i++ < 4 ?"specialResult":"normalResult); ?>'><?php
    
        .... rest of your code
    }
    

    【讨论】:

      【解决方案2】:
      <?php    
      $i = 0;
      $r = mysql_fetch_array($the_data);
      foreach($r as $row) {
          if($i <= 4) {
              // Do special styling...
          } else {
              // Do normal styling.
          }
          $i++;
      }
      ?>
      

      还是我误会了?

      【讨论】:

      • 哈哈,是的,我想我是按照你说的那样编辑它。太着急了。
      • 嗨,它的样式正确,但除非我遗漏了什么,否则它不会循环遍历数组中的数据,只是一次又一次地给我同样的数据
      【解决方案3】:

      你也可以试试:

      $i = 0;
      while ( ( $row = mysql_fetch_assoc ( $result ) ) && $i < 4 ) {
          /* Your first 4 rows */
          echo 'Special : ' . $row['title'];
          ++$i;   // Don't forget to increment
      } while ( $row = mysql_fetch_assoc () ) {
          /* Normal way */
          echo $row['title'] . ' is already outdated';
      }
      

      并且更喜欢 mysql_fetch_assoc() 而不是 mysql_fetch_array() ;)

      【讨论】:

      • 感谢您的输入,将使用 mysql_fetch_assoc - 似乎更有意义
      猜你喜欢
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      相关资源
      最近更新 更多