是否可行,如果是,我该怎么办,选择数据库中表格中的所有条目,然后在一个组中显示五个结果。
含义:一个例子是我的数据库中总共有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”或循环来检索每组数据。我也想过有关阵列的东西,但还没有得到结果。
由于
答案 0 :(得分:4)
我发现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)当你从数据库中读取行时。
答案 1 :(得分:1)
Dunno,如果我理解正确的问题,但如果你想将所有结果分组为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++;
}