Ryuk
Ryuk

Reputation: 372

How to get the array difference of multidimensional array in php?

I have 2 two arrays

$schedule = [
    "Monday" => [0 => "12:00", 1 => "01:20"],
    "Tuesday" => [0 => "04:20",1 => "12:00"],
];

$bookedSlots = [
    ["Monday" => "01:20"],
    ["Tuesday" => "04:20" ] 
];

Now I want the answer or result to return an array of the remaining available slots in which the booked slots should be eliminated from the schedule. like the result given below.

$availableSlots = $schedule - $bookedSlots; // [ "Monday" => [ 0 => "12:00"], "Tuesday" =>[ 0 => "12:00" ];

Upvotes: 0

Views: 75

Answers (1)

Vinayak Sarawagi
Vinayak Sarawagi

Reputation: 1062

Okay. So here I wrote a helper function to generalize the solution. You can use the below-mentioned function.

function find_diff($schedule, $booked_slots)
{
  $diff = [];
  foreach ($schedule as $day =>  $times) {
    $day_wise_slots = isset($booked_slots[$day]) ? $booked_slots[$day] : [];
    if (!is_array($day_wise_slots)) $day_wise_slots = [$day_wise_slots];
    $diff[$day] = array_diff($times, $day_wise_slots);

  }

  return $diff;
}

Functions used: isset and array_diff.

Hope this helps!

Upvotes: 1

Related Questions