从一个数组中的每一行获取两个日期之间的所有日期的数组

时间:2017-06-07 18:14:23

标签: php arrays date

我试图获取两个日期之间所有日期的数组,这些日期是我从每行的数据库中获取的。例如,有2017-02-02和2017-02-03有3行和2017-02-18和2017-02-20的行我想得到一个输出数组[2017-02-02, 2017-02-03,2017-02-18,2017-02-19,2017-02-20]

到目前为止,我有一个查询获取所有日期并回显开始和结束日期,以及一个脚本来获取一个日期介于2个日期之间的数组。

如何让它工作,以便将每一行的所有日期合并为一个数组?

<?php
    $result = mysqli_query($con, "SELECT * FROM invoice_line WHERE car_car_id = $id");
    while ($auto = mysqli_fetch_array($result)) {
    ?>
          <h2 class="title_car">
            <?php echo $auto['start_date'] . ' - ' . $auto['end_date'];?>
          </h2>
        <hr>
        <?php $dateRange = getDateRange($auto['start_date'], $auto['end_date']); ?>
    <?php } ?>

    <?php
    function getDateRange($startDate, $endDate, $format="Y-m-d")
{
    //Create output variable
    $datesArray = array();
    //Calculate number of days in the range
    $total_days = round(abs(strtotime($endDate) - strtotime($startDate)) / 86400, 0) + 1;
    //Populate array of weekdays and counts
    for($day=0; $day<$total_days; $day++)
    {
        $datesArray[] = date($format, strtotime("{$startDate} + {$day} days"));
    }
    //Return results array
    return $datesArray;
}

print_r($dateRange);
?>

2 个答案:

答案 0 :(得分:1)

您必须预先处理每个数组以打印日期。

<?php
$result = mysqli_query($con, "SELECT * FROM invoice_line WHERE car_car_id = $id");
while ($auto = mysqli_fetch_array($result)) {?>
  <h2 class="title_car">
    <?php echo $auto['start_date'] . ' - ' . $auto['end_date'];?>
  </h2>
  <hr>
  <?php 
  $date_text = "";
  $dateRange = getDateRange($auto['start_date'], $auto['end_date']);
  if(!empty($dateRange)){
    foreach($dateRange as $dateR){
      $date_text .= $dateR.", ";
    }
  }
  echo rtrim($date_text,", ")."<br>";
}?>

<强>输出:

2011-05-03, 2011-05-04, 2011-05-05, 2011-05-06, 2011-05-07, 2011-05-08

2011-05-20, 2011-05-21, 2011-05-22, 2011-05-23

.

.
.

答案 1 :(得分:0)

您可以使用DatePeriod课程。

你的代码会是这样的:

<?php
$rows = [
    [ new DateTime(), (new DateTime())->modify('+3 days') ],
    [ (new DateTime())->modify('+20 days'), (new DateTime())->modify('+30 days') ],
];

$dates = [];

foreach ($rows as $row) {
    $dateRange = new DatePeriod($row[0], new DateInterval('P1D'), $row[1]);

    foreach ($dateRange as $date) {
        $dates[] = $date;
    }
}

var_dump($dates);