2

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 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.