0

I would like to identify the missing dates in a PHP array

for example

this range

2013-06-12
2013-06-13
2013-06-26
2013-06-27
2013-06-29

has the following dates missing:

2013-06-14
2013-06-15
2013-06-16
...
2013-06-24
2013-06-25
2013-06-28

How can I identify the missing dates?

4

1 回答 1

7

Here's a good way to get all missing dates in an array:

<?php
$myDates = array("2013-06-12", "2013-06-13", "2013-06-26", "2013-06-27", "2013-06-29");
$missingDates = array();

$dateStart = date_create("2013-06-01");
$dateEnd   = date_create("2013-06-".date("t", mktime(0, 0, 0, 6, 1, 2013)));
$interval  = new DateInterval('P1D');
$period    = new DatePeriod($dateStart, $interval, $dateEnd);
foreach($period as $day) {
  $formatted = $day->format("Y-m-d");
  if(!in_array($formatted, $myDates)) $missingDates[] = $formatted;
}

print_r($missingDates);
?>

This will result in:

Array
(
    [0] => 2013-06-01
    [1] => 2013-06-02
    [2] => 2013-06-03
    [3] => 2013-06-04
    [4] => 2013-06-05
    [5] => 2013-06-06
    [6] => 2013-06-07
    [7] => 2013-06-08
    [8] => 2013-06-09
    [9] => 2013-06-10
    [10] => 2013-06-11
    [11] => 2013-06-14
    [12] => 2013-06-15
    [13] => 2013-06-16
    [14] => 2013-06-17
    [15] => 2013-06-18
    [16] => 2013-06-19
    [17] => 2013-06-20
    [18] => 2013-06-21
    [19] => 2013-06-22
    [20] => 2013-06-23
    [21] => 2013-06-24
    [22] => 2013-06-25
    [23] => 2013-06-28
    [24] => 2013-06-30
)
于 2013-06-05T05:11:09.903 回答