使用PHP根据描述需要输出数组

时间:2018-08-08 10:56:03

标签: php

我将此数组作为输入:

 $input=array('01-08-2018','02-08-2018','03-08-2018','05-08-2018','06-08-2018','08-08-2018','10-08-2018','11-08-2018','14-08-2018','01-09-2018','02-09-2018','10-09-2018');

我需要Expected Array :(如果连续日期中断,则需要单独的数组。)

$output=array(
              array('01-08-2018','02-08-2018','03-08-2018'),
              array('05-08-2018','06-08-2018'),
              array('08-08-2018'),
              array('10-08-2018','11-08-2018'),
              array('14-08-2018'),
              array('01-09-2018','02-09-2018'),
              array('10-09-2018')
            )
  

注意:它应该适用于31-8-2018,1-9-2018之类的日期,它应该来   在同一阵列中。

2 个答案:

答案 0 :(得分:5)

我认为这正是您所需要的     

  function isSecuencial($date1, $date2) {
    // Compares if two dates are consecutive
    $day_diff = 86400; // Difference between two days
    return strtotime($date2) - strtotime($date1) <= $day_diff;
  }

  $consecutiveIndex = 0;
  $output[$consecutiveIndex] = array($input[0]); 

  for ( $i=1; $i < sizeof($input); $i++) {
      if (isSecuencial($input[$i - 1], $input[$i])) {
          array_push($output[$consecutiveIndex], $input[$i]);
          continue;
      }
      $consecutiveIndex ++;
      $output[$consecutiveIndex] = array($input[$i]);
  }

  var_dump($output);
?>

答案 1 :(得分:2)

我最接近的事情:

$input=array('31-07-2018','01-08-2018','02-08-2018','03-08-2018','05-08-2018','06-08-2018','08-08-2018','10-08-2018','11-08-2018','14-08-2018','31-08-2018', '01-09-2018','02-09-2018','10-09-2018');

$output = [];

$prevDay = 0;

$i=0;

foreach($input as $val)  {

    $dateExploded = explode("-", $val);

    if(date('t', strtotime(date($val))) == $dateExploded[0]) {

        $dateExploded[0] = 0;

    }

    if($dateExploded[0] != $prevDay + 1) {

        $i++;

    }

    $output[$i][] = $val;

    $prevDay = $dateExploded[0];



}
print_r($output);

输出:

[1] => Array (
    [0] => 31-07-2018
    [1] => 01-08-2018
    [2] => 02-08-2018
    [3] => 03-08-2018
    )
[2] => Array (
    [0] => 05-08-2018
    [1] => 06-08-2018
    )
[3] => Array (
    [0] => 08-08-2018
    )
[4] => Array (
    [0] => 10-08-2018
    [1] => 11-08-2018
    )
[5] => Array (
    [0] => 14-08-2018
    )
[6] => Array (
    [0] => 31-08-2018
    [1] => 01-09-2018
    [2] => 02-09-2018
    )
[7] => Array (
    [0] => 10-09-2018
)