我的数据库表中有一个日期列表
例如:
"2023-12-03"
"2023-12-10"
"2023-12-17"
"2024-01-07"
"2024-01-14"
"2024-01-21"
我需要以以下形式将其返回到前端:
[1]=>
array(2) {
["year"]=>
string(4) "2024"
["months"]=>
array(3) {
[0]=>
array(2){
["monthName"]=>
string(4) "January"
['paid'] = //to be set
["dates"]=>
array(4) {
[0]=>
string(10) "2024-01-07"
[1]=>
string(10) "2024-01-14"
[2]=>
string(10) "2024-01-21"
[3]=>
string(10) "2024-01-28"
}
}
我已经成功地按年和月对日期进行了排序,但我的问题是,Monters数组键是月份名称,而不是编号索引:
$reserved_dates = array(
'2023-12-03',
'2023-12-10',
'2023-12-17',
'2023-12-24',
'2023-12-31',
'2024-01-07',
'2024-01-14',
'2024-01-21',
'2024-01-28',
'2024-02-04',
'2024-02-11',
'2024-02-18',
'2024-02-25',
'2024-12-01',
'2023-12-03',
'2024-12-08',
'2024-12-15',
);
$years = Array();
foreach($reserved_dates as $date) {
$d = $date['date'];
list($y,$m) = explode("-",$d);
$years[$y][] = $d;
}
$years = array_values($years);
foreach($years as $year)
{
$year_number = date('Y', strtotime($year[0]));
$new = array(
"year" => $year_number,
"months" => array()
);
foreach($year as $month)
{
$month_name = date('F', strtotime($month));
if(!isset($new['months'][$month_name]))
{
$new['months'][$month_name] = array();
}
array_push($new['months'][$month_name], $month);
}
array_push($reservation['reservedDates'], $new);
}
array(2) {
[0]=>
array(2) {
["year"]=>
string(4) "2023"
["months"]=>
array(1) {
["December"]=>
array(5) {
[0]=>
string(10) "2023-12-03"
[1]=>
string(10) "2023-12-10"
[2]=>
string(10) "2023-12-17"
[3]=>
string(10) "2023-12-24"
[4]=>
string(10) "2023-12-31"
}
}
}