suuuriam
suuuriam

Reputation: 747

PHP: Increment variable on date change

I'm building a class-schedule tool, where users can upload a .csv-file. I want to keep track of the dates with a variable so users can upload a schedule, which starts on the 15th of a month, for example. Therefore, I would like to increment a variable on date change. The data I receive from the csv looks like this:

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

I would like to output one day at a time:

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

and then increment $dayOfSchedule on the day change, but I don't know how to do that.

Any help is much appreciated!

Upvotes: 0

Views: 92

Answers (1)

Koala Yeung
Koala Yeung

Reputation: 7863

You're probably looking for something like this:

<?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";
}

Upvotes: 1

Related Questions