过滤PHP数组并考虑日期范围

时间:2012-11-21 17:14:02

标签: php arrays date filter merge

我有以下数组:

Array
(
    [0] => Array
    (
        [date] => 2012-01-10        
    )
    [1] => Array
    (
        [date] => 2012-01-11
    )
    [2] => Array
    (
        [date] => 2012-01-12
    )
    [3] => Array
    (
        [date] => 2012-01-15
    )
    [4] => Array
    (
        [date] => 2012-01-18
    )
    [5] => Array
    (
        [date] => 2012-01-19
    )
)

我希望将日期与他的范围结合起来。最后我需要类似下面的内容

Array
(
    [0] => Array
    (
        [from] => 2012-01-10
        [till] => 2012-01-12
    )
    [1] => Array
    (
        [from] => 2012-01-15
        [till] => 2012-01-15
    )
    [2] => Array
    (
        [from] => 2012-01-18
        [till] => 2012-01-19
    )
)

但它也应该支持广泛的范围。像2012-01-22至2012-05-14之类的东西。任何人的想法或暗示?

1 个答案:

答案 0 :(得分:0)

您的输出与上面示例中的输入不包含相同的日期。如何确定自/至日期?我们只是通过数组并在之间切换到?

function from_till($dates = array()){
  $sorted = array();
  for($i=0; $i<count($dates)-2; $i+=2){
    $sorted[] = array('from' => $dates[$i], 'till' => $dates[$i+1];
  }
  return $sorted;
}

输入:

$input = Array
(
    [0] => Array
    (
        [date] => 2012-01-10        
    )
    [1] => Array
    (
        [date] => 2012-01-11
    )
    [2] => Array
    (
        [date] => 2012-01-12
    )
    [3] => Array
    (
        [date] => 2012-01-15
    )
    [4] => Array
    (
        [date] => 2012-01-18
    )
    [5] => Array
    (
        [date] => 2012-01-19
    )
);

输出:

  $output = from_till($input);
  print_r($output);

print_r的输出

Array
(
    [0] => Array
    (
        [from] => 2012-01-10
        [till] => 2012-01-11
    )
    [1] => Array
    (
        [from] => 2012-01-12
        [till] => 2012-01-15
    )
    [2] => Array
    (
        [from] => 2012-01-18
        [till] => 2012-01-19
    )
);