是否可能,如果可以,我该怎么做,选择数据库表中的所有条目,然后在一组中同时显示五个结果。
含义:举个例子,我的数据库中有 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”或循环来检索每组数据。我也考虑过一些关于数组的事情,但还没有结果。
Thanks
I find 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;
}
当然,您可以在不首先阅读所有内容的情况下执行此操作,但如果您无论如何都要阅读所有内容,则没有太大区别,并且上面的版本可能比实现适当的中断条件更具可读性当您从数据库读取行时。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)