首页 > 解决方案 > 我如何获得缺少数组的日子?

问题描述

我有一个日期从今天 -> 今天 + 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 />";
    }
}

但它只是在呼应“未找到”。

标签: phparraysdate

解决方案


我看到您还没有找到满意的答案,也许这会对您有所帮助。

/* 
 * 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>';

工作演示


推荐阅读