2012-03-22 135 views
1

我正在修改我的新聞系統的導航,並希望使用最小的MySQL查詢來完成此操作。我已經設法將這一切都歸結爲一個查詢,但似乎有些錯誤。任何幫助將不勝感激。用PHP對層次排序的MySQL輸出進行排序

我想達到的目的是(字面)事件的下列概述,每年和每月分級排序,在該月的事件數一起:

2012 
--04 (3) 
--02 (1) 
--01 (1) 
2011 
--12 (3) 
--11 (2) 
--10 (3) 
--09 (1) 
--07 (1) 
--02 (1) 

我非常接近。我國查詢如下:

SELECT start_date, date_format(start_date, "%Y") as year, date_format(start_date, "%m") as month FROM event ORDER BY start_date desc 

然後,我的PHP循環如下:

$year   = ''; 
    $year_counter = 0; 
    $month  = ''; 
    $month_counter = 1; 
    while($row = mysql_fetch_assoc($result)){ 
     if ($year != $row['year']) { 
      $year = $row['year']; 
      $output .= $year.'<br />'; 
     } 
     if ($month == $row['month']) { 
      $month_counter++; 
     } else { 
      $month = $row['month']; 
      $output .= '--'.$month.' ('.$month_counter.')<br />'; 
      $month_counter = 1; 
     } 
    } 

這完全產生的一切,除了每月的事件,這似乎總是一個行號關閉(你可以看到與上面通緝結果的區別)。

2012 
--04 (1) 
--02 (3) 
--01 (1) 
2011 
--12 (1) 
--11 (3) 
--10 (2) 
--09 (3) 
--07 (1) 
--02 (1) 

我一直在修補這整個下午沒有成功。我認爲最好把它交給絕對的專家。一隻手好嗎?

+0

如果在表達式中放置月份循環,會發生什麼情況? – 2012-03-22 16:33:39

+0

如果我這樣做,只顯示每年的第一個月... – maartenmachiels 2012-03-22 17:54:04

回答

1

目前,你打印month_counter,然後再更新下個月。在您的while循環之前,您需要根據檢索到的第一行而不是默認值初始化變量。

if ($row = mysql_fetch_assoc($result){ 
    $year = $row['year']; 
    $month = $row['month']; 
    $month_counter = 1; //1 because you've already counted the first article 
    // print out the first year 
    $output .= $year.'<br />'; 
    while($row = mysql_fetch_assoc($result){ 
     if ($year != $row['year']) { 
      $year = $row['year']; 
      $output .= $year.'<br />'; 
     } 
     if ($month == $row['month']) { 
      // You've found one more article for this month, so increment the count 
      $month_counter++; 
     } else { 
      // You've hit a new month, so print out the information you collected 
      // about the previous month 
      $output .= '--'.$month.' ('.$month_counter.')<br />'; 
      $month = $row['month']; 
      $month_counter = 1; 
     } 
    } 
} 

月份輸出年份和輸出之間的差別,就是你也想與輸出月份相關聯的計數,而沒有與相關年度沒有附加信息。您必須在更改爲下個月之前打印該文件。

+0

謝謝,但這會產生意想不到的結果... 2012年的第一個月(即04)缺少... – maartenmachiels 2012-03-22 17:59:58

+0

對不起,我忘了提及您還需要在else塊中切換$ month = $ month =。 – aelfric5578 2012-03-23 00:13:45

+0

嗨,我不知道我是否理解正確,因爲把它放在else塊中會導致腳本只顯示年份。變量輸出應包含所有內容,並在腳本結尾處返回... – maartenmachiels 2012-03-23 14:22:44

1

$month = $row['month']; 

是放錯了地方。它將$ month變量設置爲新的月份,但它已經計算了之前幾個月的數量。

它通過while循環第一次運行時

if ($month == $row['month']) 

永遠是真實的,所以它進入別的語句,顯示當月和計數(這是1,因爲你把它設置爲1在頂部)...

+0

您應該在第一個if語句中設置$ month變量;) – snaderss 2012-03-22 16:30:52

+0

謝謝,但是如果我將第一個月的變量設置爲if聲明(年度聲明),然後2012年第一個月(4)缺失。你能否提供更多的見解? – maartenmachiels 2012-03-22 18:02:46

0

我可能在這裏做了一些錯誤,但你可以進行相應的計數每年一個月的事件,並將它們組合..像

SELECT start_date, date_format(start_date, "%Y") as year, date_format(start_date, "%m") as month, date_format(start_date, "%Y%m") gr, COUNT(id) 
FROM event 
ORDER BY start_date desc 
GROUP BY gr