PHP:以五个为一组显示来自数据库的条目? [英] PHP: display entries from Database in groups of five?

查看:99
本文介绍了PHP:以五个为一组显示来自数据库的条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以,如果可以的话,如何选择数据库中表中的所有条目,然后一次显示五个结果.

Is it possible and if so, how can I do it, to select all entries in a table in my database and then display five results at the time in one group.

含义:例如,我的数据库中总共有15条记录,那么我想像这样显示数据:

Meaning: A example is that I've 15 records total in my database, then I want to present my data like this:

<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"或循环来检索每组数据.我也考虑过一些关于数组的事情,但是还没有得出结果.

I'm not completely sure if I can do it with an SQL statement or I've to write some sort of "do...while" or loop to retrieve each set of data. I've also thought about something with arrays but haven't got up with a result.

谢谢

  • 梅斯蒂卡

推荐答案

我发现 array_chunk() 对于这种事情非常有用.

I find array_chunk() to be pretty useful for this kind of thing.

// 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)从数据库中读取行.

You can of course do this without reading them all in first but if you're going to read them all anyway, it doesn't make much difference and the above version will probably be far more readable than implementing the appropriate break condition(s) as you read the rows from the DB.

这篇关于PHP:以五个为一组显示来自数据库的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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