問題描述
是否有可能,如果有,我該怎么做,選擇我數據庫中一個表中的所有條目,然后在一組中同時顯示五個結果.
含義:例如,我的數據庫中總共有 15 條記錄,然后我想像這樣顯示我的數據:
Record[1], Record[2], Record[3], Record[4], Record[5]<div class="6-10">Record[6], Record[7], Record[8], Record[9], Record[10]
是否有可能,如果有,我該怎么做,選擇我數據庫中一個表中的所有條目,然后在一組中同時顯示五個結果.
含義:例如,我的數據庫中總共有 15 條記錄,然后我想像這樣顯示我的數據:
Record[1], Record[2], Record[3], Record[4], Record[5]<div class="6-10">Record[6], Record[7], Record[8], Record[9], Record[10]
<div class="11-15">Record[11], Record[12], Record[13], Record[14], Record[15]
我不確定是否可以使用 SQL 語句來完成,或者我必須編寫某種do...while"或循環來檢索每組數據.我也想過一些關于數組的事情,但沒有得到結果.
謝謝
我發現 array_chunk()
對這種事情非常有用.
//將所有記錄拉入一個數組$query = mysql_query('SELECT * FROM mytable');$rows = array();而 ($row = mysql_fetch_array($query)) {$rows[] = $row;}//這將一個數組變成一個數組數組,其中每個子數組是//5 個原始條目$groups = array_chunk($rows, 5);//一個接一個地處理每一組$開始= 1;foreach ($groups as $group) {$end = $start + 4;//$group 是一組 5 行.按要求處理$content = implode(', ', $group);回聲<<<END<div class="$start-$end">$content</div>結尾;$開始 += 5;}
您當然可以不先閱讀所有內容而執行此操作,但是如果您無論如何都要閱讀所有內容,則沒有太大區別,并且上述版本可能比實現適當的中斷條件更具可讀性(s) 當您從數據庫中讀取行時.
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.
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>
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.
Thanks
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;
}
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:以五個為一組顯示數據庫中的條目?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!