0

好的,我有一个名为“post_date”的列的数据库。每个条目都是 YMD,所以就像 2013-06-01。

我想要做的是使用 PHP 在我的页面上显示,如下所示:

2013
06-01, 05-31, 05-30, etc

2012
06-01, 05-31, 05-30, etc

2011
06-01, 05-31, 05-30, etc

月份和日期是数据库中的任何内容。我试过 GROUP BY YEAR(post_date) 但没有成功。我怎样才能做到这一点?谢谢。

4

3 回答 3

0

你有没有尝试过:

SELECT YEAR(post_date) AS year, 
       MONTH(post_date) AS month, 
       DAY(post_date) AS day 
FROM archives 
ORDER BY YEAR(post_date) ASC, 
         MONTH(post_date) ASC, 
         DAY(post_date) ASC

编辑

$stmt = $db->prepare("
    SELECT YEAR(post_date) AS year, 
        MONTH(post_date) AS month, 
        DAY(post_date) AS day 
    FROM archives 
    WHERE YEAR(post_date) = :currentYear 
    ORDER BY YEAR(post_date) ASC, 
        MONTH(post_date) ASC, 
        DAY(post_date) ASC
");

 $startYear = 2003;
 $endYear = 2013;

 for($y = $startYear; $y<=$endYear; $y++)
 {
     echo $y . '<br />';

     $stmt->bindValue(':currentYear', $y);
     $stmt->execute();

     foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row)
     {
         echo $row['month'] . '-' . $row['day'] . '; ';
     }
 }
于 2013-06-01T20:19:41.983 回答
0

到目前为止,我有:

SELECT YEAR(post_date) AS year, MONTH(post_date) AS month, DAY(post_date) AS day FROM archives GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY YEAR(post_date) DESC, MONTH(post_date) DESC, DAY(post_date) DESC

但是最后 2 行没有显示。

我得到的格式是:2013 0601

2013 0531

所以我很困惑如何在没有年份的情况下循环,但被循环。

于 2013-06-01T20:37:39.787 回答
0

选择所有需要的行,然后在 php 中使用循环:

foreach($sqlArray as $result){
    $date = explode(' ',$result['post_date']);
    $Ymd = explode('-',$date);
    $resultArray[$Ymd[0]][] = $Ymd[1].'-'.$Ymd[2];
}
foreach($resultArray as &$array){
    arsort($array);
}

或尝试array_map($resultArray,'arsort');然后

foreach($resultArray as $year=>$dates){
echo $year;
    foreach($date as $date){
echo $date;
     }
}
于 2013-06-01T20:38:08.757 回答