我正在创建一个计划,我想按时间范围分组,例如:月份号2(二月)已预订。这就是为什么不在$free_time_frame
中
$free_time_frame = [];
$start = new DateTime("2022-01-01");
$end = new DateTime("2022-12-31");
$interval = new DateInterval("P1M"); // 1 month interval
$period = new DatePeriod($start, $interval, $end);
$seasons = [8,2];
foreach ($period as $date) {
if (in_array($date->format("n"), $seasons)) {
// Skip the rest of the loop if the current month is in the $seasons array
continue;
}
// Set the start date to the first day of the month
$start_date = new DateTime($date->format("Y-m-01"));
// Set the end date to the last day of the month
$end_date = new DateTime($date->format("Y-m-t"));
// Calculate the number of days between the start and end dates
$diff = $start_date->diff($end_date);
$days = $diff->days + 1; // Add 1 to include the end date
$free_time_frame[] = [
"from" => $start_date->format("Y-m-d"),
"to" => $end_date->format("Y-m-d"),
"slot" => $days,
];
$start->modify("+1 month");
}
这就是结果:
[{
"from": "2022-01-01",
"to": "2022-01-31",
"frame": 31,
"season": 1
}, {
"from": "2022-03-01",
"to": "2022-03-31",
"frame": 31,
"season": 3
}, {
"from": "2022-04-01",
"to": "2022-04-30",
"frame": 30,
"season": 4
}, {
"from": "2022-05-01",
"to": "2022-05-31",
"frame": 31,
"season": 5
}, {
"from": "2022-06-01",
"to": "2022-06-30",
"frame": 30,
"season": 6
}, {
"from": "2022-07-01",
"to": "2022-07-31",
"frame": 31,
"season": 7
}, {
"from": "2022-09-01",
"to": "2022-09-30",
"frame": 30,
"season": 9
}, {
"from": "2022-10-01",
"to": "2022-10-31",
"frame": 31,
"season": 10
}, {
"from": "2022-11-01",
"to": "2022-11-30",
"frame": 30,
"season": 11
}, {
"from": "2022-12-01",
"to": "2022-12-31",
"frame": 31,
"season": 12
}]
我想要完成的任务:
如您所见,我有一个平面数组,包含除二月以外的所有月份。我想将$season
之前的月份放在一个数组中,将$season
之后的月份放在另一个数组中,始终放在$free_time_frame
内
预期结果:
[
[
{
"from":"2022-01-01",
"to":"2022-01-31",
"frame":31,
"season":1
}
],
[
{
"from":"2022-03-01",
"to":"2022-03-31",
"frame":31,
"season":3
},
{
"from":"2022-04-01",
"to":"2022-04-30",
"frame":30,
"season":4
},
{
"from":"2022-05-01",
"to":"2022-05-31",
"frame":31,
"season":5
},
{
"from":"2022-06-01",
"to":"2022-06-30",
"frame":30,
"season":6
},
{
"from":"2022-07-01",
"to":"2022-07-31",
"frame":31,
"season":7
}
],
[
{
"from":"2022-09-01",
"to":"2022-09-30",
"frame":30,
"season":9
},
{
"from":"2022-10-01",
"to":"2022-10-31",
"frame":31,
"season":10
},
{
"from":"2022-11-01",
"to":"2022-11-30",
"frame":30,
"season":11
},
{
"from":"2022-12-01",
"to":"2022-12-31",
"frame":31,
"season":12
}
]
]
1条答案
按热度按时间yizd12fk1#
PHP不支持“多维数组”,你需要的是嵌套数组。
当赛季结束的时候添加空数组并使用它。用第一个嵌套数组初始化。
您可能希望扩展您的算法,以便在添加新的嵌套数组之前检查最新的嵌套数组是否为空,例如,当
$seasons
与[2,3,10]
相似时。