如何合并数组中的日期范围

时间:2014-10-01 23:48:45

标签: php arrays date

我在数组中有一些日期范围,并希望合并它们。结果是具有最低开始日期和最高结束日期的日期范围。这些是不同情况下的一些样本。 案例1:

$case1 = array(
    array(
        'start_date' => '2014-10-06',
        'end_date' => '2014-10-23',
    ),
    array(
        'start_date' => '2014-10-10',
        'end_date' => '2014-10-12',
    ),
    array(
        'start_date' => '2014-10-17',
        'end_date' => '2014-10-19',
    ),
);

//expected
$res1 = array('start_date' => '2014-10-06', 'end_date' => '2014-10-23');

案例2:

$case2 = array(
    array(
        'start_date' => '2014-10-06',
        'end_date' => '2014-10-23',
    ),
    array(
        'start_date' => '2014-09-10',
        'end_date' => '2014-10-12',
    ),
    array(
        'start_date' => '2014-10-17',
        'end_date' => '2014-10-19',
    ),
);

//expected
$res2 = array('start_date' => '2014-09-10', 'end_date' => '2014-10-23');

案例3:

$case3 = array(
    array(
        'start_date' => '2014-10-06',
        'end_date' => '2014-10-23',
    ),
    array(
        'start_date' => '2014-10-10',
        'end_date' => '2014-10-12',
    ),
    array(
        'start_date' => '2014-10-17',
        'end_date' => '2014-11-12',
    ),
);

//expected
$res3 = array('start_date' => '2014-10-06', 'end_date' => '2014-11-12');

非常感谢您的帮助。谢谢你们

2 个答案:

答案 0 :(得分:0)

您可以使用任何内置的php数组函数:

array_merge_recursivearray_replace_recursive

答案 1 :(得分:0)

由于您只是针对最低和最高日期,只需将它们转换为秒,然后对它们进行排序,然后获得第一个和最后一个:

$case1 = array(
    array(
        'start_date' => '2014-10-06',
        'end_date' => '2014-10-23',
    ),
    array(
        'start_date' => '2014-10-10',
        'end_date' => '2014-10-12',
    ),
    array(
        'start_date' => '2014-10-17',
        'end_date' => '2014-10-19',
    ),
);

$all_dates = array();
array_walk_recursive($case1, function($date) use (&$all_dates){ $all_dates[] = strtotime($date); }); // put them all inside and convert them to seconds
sort($all_dates); // normal sorting
$res1 = array('start_date' => date('Y-m-d', reset($all_dates)), 'end_date' => date('Y-m-d', end($all_dates))); // then assign the first element = start, and end element = end date
echo '<pre>';
print_r($res1);