PHP:データベースのエントリを5つのグループに表示しますか?
-
05-07-2019 - |
質問
データベース内のテーブル内のすべてのエントリを選択し、1つのグループに一度に5つの結果を表示することは可能です。
意味:例として、データベースに合計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」のような記述をする必要があるかどうかは完全にはわかりません。または、ループしてデータの各セットを取得します。また、配列を使用して何かを考えましたが、結果に追いついていません。
ありがとう
- 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つのグループにグループ化する場合は、Dunno:
$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