Search code examples
phparrayssortingmultidimensional-array

Sort second level arrays of a three-level array by column


Regarding this multidimensional array:

[
    7 => [
        ['12:45', 'E1', 'B EXTREME 30'],
        ['10:15', 'E1', 'B SHAPE 30'],
    ],
    1 => [
        ['09:30', 'E2', 'CYCLING VIRTUAL 50'],
        ['10:30', 'E1', 'BODY PUMP VIRTUAL 60'],
        ['11:45', 'E1', 'BODY BALANCE VIRTUAL 60'],
    ],
    2 => [
        ['14:45', 'E2', 'CYCLING VIRTUAL 50'],
        ['17:00', 'E1', 'POSTURA ALONGAMENTO 60'],
        ['09:15', 'E1', 'BODY PUMP 50'],
    ],
];

The first key, of each first level array, are days of the week (day 7, day 1 and day 2).

The arrays inside each first level array contain hour (09:45), rooms (E1) and description (B EXTREME 30).

I tried to sort this multidimensional array by the second levels array hour value. I used usort(), ksort(), array_multisort(), and some custom made functions for sorting the array as I need without luck.

The inside arrays must be sorted by ascending order, like this (example with day 2):

09:15 -> 14:45 -> 17:00

How can I achieve this?


Solution

  • Assuming your data is called $data. Iterate the outer array, and apply a sort on each mid-level array, based on the time-part (in the innermost arrays). As your times are always formatted as "hh:ss", a string comparison in the usort callback does the job:

    foreach ($data as &$events) {
        usort($events, function($a, $b) {
            return strcmp($a[0], $b[0]);
        });
    }
    

    Note the & in the foreach: this makes sure you sort the original data, and not a copy of it.

    If you want to create a new array, let's say $result, then do this (no & here!):

    foreach ($data as $day => $events) {
        usort($events, function($a, $b) {
            return strcmp($a[0], $b[0]);
        });
        $result[$day] = $events;
    }