php - 我如何获得缺少数组的日子?
问题描述
我有一个日期从今天 -> 今天 + 14 天的数组。像这样的结构:
Array
(
[0] => Array
(
[0] => Array
(
[datum] => DateTimeImmutable Object
(
[date] => 2019-11-04 16:30:00.000000
[timezone_type] => 1
[timezone] => +01:00
)
)
)
[1] => Array
(
[0] => Array
(
[datum] => DateTimeImmutable Object
(
[date] => 2019-11-05 17:00:00.000000
[timezone_type] => 1
[timezone] => +01:00
)
)
)
)
现在我想知道,缺少哪些日期。
我尝试这样的事情:
for ($i = 0; $i < 14; $i++) {
$checkDate = DateTime::createFromFormat('Y-m-d H:i', date('Y-m-d H:i'))->add(new DateInterval("P".$i."D"));
if(array_search($checkDate, array_column($freeTime, 'datum')) !== false) {
echo "FOUND<br />";
} else {
echo "Not Found<br />";
}
}
但它只是在呼应“未找到”。
解决方案
我看到您还没有找到满意的答案,也许这会对您有所帮助。
/*
* step 1: create benchmark array ($benchmarkDates)
* containing all consecutive dates from $start
*/
$start = '2019-10-27 16:30:00';
$days = 14; // total number of days (including $start)
$dateObj = new DateTimeImmutable($start);
$benchmarkDates[] = $dateObj->format('Y-m-d H:i:s'); // store the first bench date
for ($i = 1; $i < $days; $i++) {
$period = 'P' . $i . 'D';
$interval = new DateInterval($period);
$dateObj0 = $dateObj->add($interval);
$benchmarkDates[] = $dateObj0->format('Y-m-d H:i:s'); // store the next bench date
}
/*
* step 2: retrieve dates from DateTimeImmutable objects
* in the array you want to check for date-gaps ($subject).
*/
foreach ($subject as $key => $value) {
foreach ($value as $key => $value) {
$subjectDates[] = $value['datum']->format('Y-m-d H:i:s'); // store dates
}
}
/*
* step 3: store missing dates
* check subject against benchmark
*/
foreach($benchmarkDates as $key => $value) {
if(!in_array($value, $subjectDates)) {
$missingDates[] = $value;
}
}
echo '<pre>';
print_r($missingDates);
echo '</pre>';
工作演示
推荐阅读
- c# - 在 1 台计算机上打开两个带有 transparancy="true" 的 wpf 应用程序时,只有一个显示
- spring-data-jpa - Spring Data Jpa - 获取 MaxID + 1 的存储库查询?
- python - 为什么base64编码直接返回字节而不是字符串?
- android - 如何更改 DatePickerDialog 中按钮的背景颜色?
- abap - 如何在打印 RECN 合同时检索 is_sfparam-content?
- sql-server - 如何捕获 where 子句并在存储过程调用中使用它
- javascript - 在视图目录中找不到视图“索引”
- javascript - JavaScript 函数未在 c# 代码中定义
- javascript - vue.js 中锚链接点击事件中的水平滚动行为
- excel - VBA 运行时错误“1004”:应用程序定义的或对象定义的错误。我究竟做错了什么?