【问题标题】:PHP: display entries from Database in groups of five?PHP:以五个为一组显示来自数据库的条目?
【发布时间】:2010-12-20 14:16:33
【问题描述】:

是否有可能,如果可以,我该怎么做,选择我数据库中表中的所有条目,然后在一组中同时显示五个结果。

含义:一个例子是我的数据库中总共有 15 条记录,那么我想这样呈现我的数据:

<div class="1-5">Record[1], Record[2], Record[3], Record[4], Record[5]</div>

<div class="6-10">Record[6], Record[7], Record[8], Record[9], Record[10]</div>

<div class="11-15">Record[11], Record[12], Record[13], Record[14], Record[15]</div>

我不完全确定是否可以使用 SQL 语句来完成,或者我必须编写某种“do...while”或循环来检索每组数据。我也想过一些关于数组的事情,但还没有得到结果。

谢谢

  • 梅斯蒂卡

【问题讨论】:

    标签: php sql database loops while-loop


    【解决方案1】:

    我发现array_chunk() 对这类事情非常有用。

    // pull all the records into an array
    $query = mysql_query('SELECT * FROM mytable');
    $rows = array();
    while ($row = mysql_fetch_array($query)) {
      $rows[] = $row;
    }
    
    // this turns an array into an array of arrays where each sub-array is
    // 5 entries from the original
    $groups = array_chunk($rows, 5);
    
    // process each group one after the other
    $start = 1;
    foreach ($groups as $group) {
      $end = $start + 4;
    
      // $group is a group of 5 rows. process as required
      $content = implode(', ', $group);
    
      echo <<<END
    <div class="$start-$end">$content</div>
    
    END;
      $start += 5;
    }
    

    您当然可以在不先阅读所有内容的情况下执行此操作,但是如果您还是要阅读所有内容,则没有太大区别,并且上述版本可能比实现适当的中断条件更具可读性(s) 当您从数据库中读取行时。

    【讨论】:

      【解决方案2】:

      不知道我是否正确理解了这个问题,但是如果您想将所有结果分组为 5 组:

      
      $i =1;    
      while ($row = mysql_fetch_array($query)) {
       echo $row['name']."\n";
       if ($i % 5 == 0)
       {
         echo 'hr'; // Or any other separator you want
       }
       $i++;
      }
      

      【讨论】:

      • 这个答案非常好,快捷的解决方案...谢谢哥们
      猜你喜欢
      • 2020-07-12
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      相关资源
      最近更新 更多