首页 > 解决方案 > PHP:日期变化的增量变量

问题描述

我正在构建一个课程安排工具,用户可以在其中上传 .csv 文件。我想用一个变量来跟踪日期,这样用户就可以上传一个时间表,例如从一个月的 15 号开始。因此,我想在日期更改时增加一个变量。我从 csv 收到的数据如下所示:

array(
  array(
    '1',
    '2019-10-15',
    'Orientation / Team Building',
    '371',
    '',
    '0',
    '',
  ),
  array(
    '1',
    '2019-10-16',
    'Study Skills',
    '371',
    '',
    '0',
    '',
  ),
);

我想一次输出一天:

$currentMonth = date('F');
$dayOfSchedule = 0;
while ($dayOfSchedule < sizeof($schedule[$currentMonth]){
   echo $schedule[$currentMonth][$dayOfSchedule][2]; //output the class etc.
}

然后在当天更改时增加 $dayOfSchedule ,但我不知道该怎么做。

任何帮助深表感谢!

标签: phploopsdate

解决方案


您可能正在寻找这样的东西:

<?php

$data = array(
  array(
    1,
    '2019-10-16',
    'Study Skills',
    '371',
    '',
    0,
    '',
  ),
  array(
    1,
    '2019-10-16',
    'Mathematics',
    '371',
    '',
    0,
    '',
  ),
  array(
    1,
    '2019-10-15',
    'Orientation / Team Building',
    371,
    '',
    0,
    '',
  ),
);

// map rows according to the date
$schedule = array_reduce($data, function ($accu, $row) {
  $date = \DateTime::createFromFormat('Y-m-d', $row[1]);
  $accu[$date->format('F')][$date->format('j')][] = $row;
  return $accu;
}, []);

// sort the days and months
ksort($schedule);
array_walk($schedule, function (&$month_schedule) {
  ksort($month_schedule);
});

$today = date('j'); // day of month today
if (isset($schedule[date('F')])) {
  foreach ($schedule[date('F')] as $day => $rows) {
    if ((int) $day >= (int) $today) {
      echo "  Day of Month: $day\n";
      foreach ($rows as $key => $row) {
        echo "    Class({$key}): {$row[2]}\n";
      }
    }
  }
  echo "\n";
}

推荐阅读