0

我有日期数组,例如:

$dates = array('2013-01-30', '2013-01-31', '2013-02-01', '2013-02-02', '2013-04-04', '2013-04-05', '2013-04-06');

http://codepad.org/Lnh0TYHW

为这些日期设置间隔的最佳方法是什么?我想收到:

$interval = array(
     array('first' => '2013-01-30', 'last' => '2013-02-02'),
     array('first' => '2013-04-04', 'last' => '2013-04-06')
);

首先这是数组中的第一个日期或尚未分配的第一个日期。最后日期,这是下一个日期为空的日期。例如 - 2013-02-02 - next 应该是 2013-02-03,但这不在数组中,所以 2013-02-02 是间隔中的最后一个。

4

2 回答 2

0

To find contiguous date ranges, for each date you have to determine whether it follows the end of the last range. If it does, you expand that range; if not, you create a new range.

$dates = array('2013-01-30', '2013-01-31', '2013-02-01', '2013-02-02', '2013-04-04', '2013-04-05', '2013-04-06');

$ranges = array();
$current = 0;

foreach ($dates as $date) {
    if (isset($ranges[$current])) {
        // existing range
        if ($date == date('Y-m-d', strtotime("{$ranges[$current]['last']} +1 day"))) {
            $ranges[$current]['last'] = $date; // expand
        } else {
            ++$current; // move to a new range
        }
    }
    // create new range
    if (!isset($ranges[$current])) {
        // create new range
        $ranges[$current] = array('first' => $date, 'last' => $date);
    }
}

print_r($ranges);
于 2013-06-10T08:37:06.777 回答
0

这是一个示例函数及其用法,我有时会自己使用。更改函数中的格式以使其看起来像您的日期

    function dateRange( $first, $last, $step = '+1 day', $format = 'Y/m/d' ) {

        $dates = array();
        $current = strtotime( $first );
        $last = strtotime( $last );

        while( $current <= $last ) {

            $dates[] = date( $format, $current );
            $current = strtotime( $step, $current );
        }

        return $dates;
    }

print_r( dateRange( '2010/07/26', '2010/08/05') );

Array (

[0] => 2010/07/26

[1] => 2010/07/27

[2] => 2010/07/28

[3] => 2010/07/29

[4] => 2010/07/30

[5] => 2010/07/31

[6] => 2010/08/01

[7] => 2010/08/02

[8] => 2010/08/03

[9] => 2010/08/04

[10] => 2010/08/05

)

也跳过几周:

print_r( dateRange( '2010/07/26', '2010/08/05', '+1 week') );

Array (

[0] => 2010/07/26

[1] => 2010/08/02

)

所以在你的情况下,你会像这样使用它:

print_r(dateRange($interval[0]['first'], $interval[0]['last']));
于 2013-06-10T08:23:53.197 回答