0

I am comparing 2 arrays but after applying array_diff it returns the result in the object form. Have a look at the below code and result

<?php
        $schedule =  ['Monday'=>['12:00','01:20'],'Tuesday'=>['04:00','12:00','20:00']];
        $booked_slots =  ['Monday'=>['12:00'],'Tuesday'=>['20:00']];
        
        $diff = [];
        foreach ($schedule as $day =>  $times) {
            $day_wise_slots = isset($booked_slots[$day]) ? $booked_slots[$day] : [];
            $diff[$day] = array_diff($times, $day_wise_slots);
        }
        
        echo json_encode($diff);
?>

Result : {"Monday":{"1":"01:20"},"Tuesday":["04:00","12:00"]}

Desired Output: {"Monday":["01:20"],"Tuesday":["04:00","12:00"]}

1
  • 1
    The indexes need to be contiguous and start from 0. Run array_values() on the result of array_diff(). Commented Jun 26, 2020 at 17:54

1 Answer 1

1

array_diff perserves keys of original array. You need to reinitialize array to not have array keys in json. You can use array_values to get a reinitialized array keys

<?php
       $schedule =  ['Monday'=>['12:00','01:20'],'Tuesday'=>['04:00','12:00','20:00']];
       $booked_slots =  ['Monday'=>['12:00'],'Tuesday'=>['20:00']];
       
       $diff = [];
       foreach ($schedule as $day =>  $times) {
           $day_wise_slots = isset($booked_slots[$day]) ? $booked_slots[$day] : [];
           $diff[$day] = array_values(array_diff($times, $day_wise_slots));
       }
       
       echo json_encode($diff);
?>
Sign up to request clarification or add additional context in comments.

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.