How to add incrementally to multidim array PHP?

Viewed 31

I'm pulling many rows like this from database

$rows = [
    ['id' => 3, 'course_name' => 'GSG2', 'course_day' => 'Monday', 'course_starts_at' => '01:30:00'],
    ['id' => 2, 'course_name' => 'Look1', 'course_day' => 'Wednesday', 'course_starts_at' => '03:10:00']
]

And I need to make one multidim array from it which would have weekdays as keys and arrays of rows as values. Because I need keys to be present even if the day is empty, I did this first

$timetable = [
  ['Monday' => ''],
  ['Tuesday' => ''],
  ['Wednesday' => ''],
  ['Thursday' => ''],
  ['Friday' => ''],
];

And then I'm doing this

foreach ($rows as $row) {
  switch ($row['course_day']) {
    case "Monday":
      $timetable['Monday'] = $row;
      break;
    case "Tuesday":
      $timetable['Tuesday'] = $row;
      break;
    case "Wednesday":
      $timetable['Wednesday'] = $row;
      break;
    case "Thursday":
      $timetable['Thursday'] = $row;
      break;
    case "Friday":
      $timetable['Friday'] = $row;
      break;
  }
}

But then the resulting multidim array has only one course (its last iteration) for each day. I tried using += instead of = but that didn't work. Have you got any suggestions please?

2 Answers

The simplest modification to your could would be as follows:

$timetable = [
    'Monday' => [],
    'Tuesday' => [],
    'Wednesday' => [],
    'Thursday' => [],
    'Friday' => []
];

foreach ($rows as $row) {
    $courseDay = $row['course_day'];
    if (isset($timetable[$courseDay])) {
        $timetable[$courseDay][] = $row;
    }
}

First create the timetable with indexes as the week days and later if weekday matches add the event. It also allows you to limit which days you support by adding or removing them from the timetable variable.

Try doing it this way

foreach ($rows as $row) {
  switch ($row['course_day']) {
    case "Monday":
      $timetable['Monday'][] = $row;
      break;
    case "Tuesday":
      $timetable['Tuesday'][] = $row;
      break;
    case "Wednesday":
      $timetable['Wednesday'][] = $row;
      break;
    case "Thursday":
      $timetable['Thursday'][] = $row;
      break;
    case "Friday":
      $timetable['Friday'][] = $row;
      break;
  }
}
Related