2012-03-22 59 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