2

我有以下数组:

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 之类的东西。任何人的想法或提示?

4

1 回答 1

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
    )
);
于 2014-06-07T20:29:26.903 回答