0

I have two arrays that have values that work together, one with an array of time slots and the other with an array of no of slots per time from left to right. Below is what the arrays look like:

$timeslot = ['22:00', '10:00', '18:00'];
$no_of_slot = [5,10,34];

From about 22:00 = 5,10:00 = 10 and 18:00 = 34 I was able to sort array $timeslot so that the array can be in increasing order i.e ````['10:00','18:00','22:00']`` with below code:


function date_compare($element1, $element2) {
    $datetime1 = strtotime($element1);
    $datetime2 = strtotime($element2);
    return $datetime1 - $datetime2;
}

// Sort the array
usort($timeslot, 'date_compare');

But since they work together i.e $timeslot and $no_of_slot I will like when the to rearrange is done for $timeslot then $no_of_slot should be done too and my final result will be like below:

$timeslot = ['10:00', '18:00', '22:00'];
$no_of_slot = [10,34,5];

Is there a way I can sort them together?

  • You don't have a multidimensional array, you have two 1-dimensional arrays. Anyway, you can sort them together using `array_multisort()`. – Barmar Feb 01 '23 at 15:38
  • In general, you'll find that things will be easier if you collect all related data together in one array, rather than separate array. Use an array of associative arrays: `[['no' => 5, 'timeslot' => '22:00'], ['no' => 10, 'timeslot' => '10:00'], ['no' => 34, 'timeslot' => '18:00']]` – Barmar Feb 01 '23 at 15:40
  • @YourDeveloper If your timeslot values are always `hh:mm` formatted (zero padded), then you don't need to compare the strings as time expressions with `strtodate()`; you can compare them as simple strings. – mickmackusa Feb 01 '23 at 23:12

0 Answers0