PHP:显示项目数据库在小组的五个?
-
05-07-2019 - |
题
它是可能的,如果是这样,我怎么可以这样做,选择的所有条目中的一个表格在我的数据库,然后显示五个结果当时在一个组。
意义:一个例子是,我已经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 statement或者我已经写入某种形式的"做...同时"或循环检索每个集的数据。我也想过的东西与阵列,但没有得到一个结果。
感谢
- Mestika
解决方案
我找到 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)作为你读的行DB。
其他提示
不知道,如果我理解正确的问题,但如果妳想要群组的所有结果在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++;
}
不隶属于 StackOverflow