我试图从mysql表的date
列中获取所有年份和月份。预期的结果应该用在一个meny中,应该看起来像这样:
**2015**
oct
sep
aug
july
june
may
apr
mars
feb
jan
**2014**
dec
nov
oct
sep
aug
july
june
may
apr
mars
feb
jan
**2013**
dec
nov
oct
sep
aug
july
june
may
apr
mars
feb
jan
起初我试过这个:
public static function arrange(){
$database = DatabaseFactory::getFactory()->getConnection();
//Select all years
$sql = "SELECT DISTINCT YEAR(date) FROM MOCK_DATA ORDER by YEAR(date) DESC";
$query = $database->prepare($sql);
$query->execute();
$years = $query->fetchAll();
//Select all months in numbers
$sql = "SELECT DISTINCT MONTH(DATE) AS month_num FROM MOCK_DATA WHERE YEAR(DATE) = :year ORDER BY DATE DESC";
$query = $database->prepare($sql);
$query->execute(array(':year' => $years));
$query->fetchAll();
$months_int = array(
1=>'januari',
2=>'februari',
3=>'mars',
4=>'april',
5=>'maj',
6=>'juni',
7=>'juli',
8=>'agusti',
9=>'september',
10=>'oktober',
11=>'november',
12=>'december');
$months_string = array();
foreach($months_int as $month){
$months_string[] = strtr($month,$months_int);
}
return $months_string;
}
但我没有得到它的工作,它似乎更加“先进”然后neccesery,因为经过一个小时左右的谷歌搜索 - 我发现了这个:
SELECT DISTINCT CONCAT(MONTHNAME(date), ' ', YEAR(date)) AS `Month`
FROM MOCK_DATA
ORDER BY date DESC
来自docs。
所以,遗憾的是我无法使用该查询。但是发现那个查询认为有一个查询可以产生我正在寻找的东西!
我认为我的查询应该给我一个类似$data->years
和$data->months
的stdClass。所以我可以用
foreach($data->years as $years){
echo $years;
foreach($data->months as $months){
echo $months;}
}
我的问题是:是否存在mysql查询,它为我提供了当年的所有years
和所有months
? 如果不是:我如何使用php执行此操作?