好的我有一个名为“post_date”的数据库。每个条目都是Y-M-D,所以就像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),但没有成功。我怎样才能做到这一点?感谢。
答案 0 :(得分: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'] . '; ';
}
}
答案 1 :(得分: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
但最后两行没有显示。
我得到的格式是: 2013 0601
2013 0531
所以我很困惑如何在循环中没有年份的情况下循环,但是循环播放。
答案 2 :(得分: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;
}
}