我偶然發現了一個我認爲很容易解決的問題,但似乎讓我發瘋。所以,我試圖按時間對一些MySQL記錄進行排序,然後按日期對它們進行排序。例如,這裏是我的MySQL數據:PHP/MySQL:按時間排序,然後按日期排序
+----+------------+----------+---------------------------+--------+
| id | date | time | entry | status |
+----+------------+----------+---------------------------+--------+
| 21 | 2011-10-05 | 09:42:06 | All systems online. | 1 |
| 22 | 2011-10-05 | 09:43:09 | Maintenance starting. | 2 |
| 23 | 2011-10-04 | 08:42:06 | Systems online and ready. | 1 |
| 24 | 2011-10-05 | 09:44:30 | Systems are offline. | 0 |
+----+------------+----------+---------------------------+--------+
所以,我用得到一切排序的查詢是:
SELECT * FROM status order by date ASC;
其產生以下結果:
+----+------------+----------+---------------------------+--------+
| id | date | time | entry | status |
+----+------------+----------+---------------------------+--------+
| 21 | 2011-10-05 | 09:42:06 | All systems online. | 1 |
| 22 | 2011-10-05 | 09:43:09 | Maintenance starting. | 2 |
| 24 | 2011-10-05 | 09:44:30 | Systems are offline. | 0 |
| 23 | 2011-10-04 | 08:42:06 | Systems online and ready. | 1 |
+----+------------+----------+---------------------------+--------+
PHP輸出是問題。因此,輸出現在的問題是:
2011年10月4日
- 系統聯機並準備就緒。 [上午8點42分]
2011年10月5日
所有系統聯機。 [09:42 AM]
維護開始。 [09:43 AM]
系統處於脫機狀態。 [上午09點44分]
我想要的輸出是:
2011年10月5日 - 系統處於脫機狀態。 [09:44 AM]
維護開始。 [09:43 AM]
所有系統在線。 [上午09時42分]
2011年10月4日
- 系統聯機並準備就緒。 [08:42 AM]
基本上,我想按日期分組的所有東西(最新的第一個),我希望最近的時間在頂部,而不是底部。
這是我的PHP代碼:
function getUpdates() {
global $db;
$updchk = "";
$entries = $db->GetAll("SELECT * FROM status order by date DESC;");
if (!$entries) { ?>
<p>No entries in the database, yet.</p>
<?php } else
foreach ($entries as $entry) {
if (ConvertDate($entry['date']) != $updchk) { ?>
<h4><?php echo ConvertDate($entry['date']); ?></h4>
<p><?php echo $entry['entry']; ?><span class="timestamp"> [<?php echo strftime('%I:%M %p', strtotime($entry['time'])); ?>]</span></p>
<?php $updchk = ConvertDate($entry['date']); ?>
<?php } else { ?>
<p><?php echo $entry['entry']; ?><span class="timestamp"> [<?php echo strftime('%I:%M %p', strtotime($entry['time'])); ?>]</span></p>
<?php }
} ?>
<?php } ?>
任何幫助表示讚賞。
謝謝!
哇工作,這很簡單。 – drewrockshard
+1爲您的速度! ;) – JellyBelly