Chris Beckett Chris Beckett - 1 month ago 7
PHP Question

How to sort array by startTime?

How would I sort this array by startTime?

Code:

function arraySorter($a, $b) {
return strtotime($a->startTime) - strtotime($b->startTime);
}

usort($this->meetingSlotsTaken, 'arraySorter');

echo "<pre>";
print_r($this->meetingSlotsTaken);
echo "</pre>";


I'm doing my code dynamically, I don't want to manually enter the keys like the following:

usort($this->meetingSlotsTaken[0]['2016-10-07 14:10:00'], 'arraySorter');


Print out:

Array
(
[0] => Array
(
[2016-10-07 14:10:00] => Array
(
[0] => stdClass Object
(
[pupil_id] => 48307
[fullname] => Callum Lacey
[grade_id] => 87
[meeting_id] => 1812
[slot_id] => 31306
[title] => Parent Evening 1 - 2016-10-07 14:00
[startTime] => 2016-10-07 14:10:00
[endTime] => 2016-10-07 14:20:00
)

[1] => stdClass Object
(
[pupil_id] => 79571
[fullname] => Daniel Lacey
[grade_id] => 87
[meeting_id] => 1812
[slot_id] => 31305
[title] => Parent Evening 1 - 2016-10-07 14:00
[startTime] => 2016-10-07 14:00:00
[endTime] => 2016-10-07 14:10:00
)

[2] => stdClass Object
(
[pupil_id] => 48307
[fullname] => Callum Lacey
[grade_id] => 87
[meeting_id] => 1816
[slot_id] => 31322
[title] => 2016-10-07 14:15
[startTime] => 2016-10-07 14:20:00
[endTime] => 2016-10-07 14:25:00
)

[3] => stdClass Object
(
[pupil_id] => 79571
[fullname] => Daniel Lacey
[grade_id] => 87
[meeting_id] => 1816
[slot_id] => 31323
[title] => 2016-10-07 14:15
[startTime] => 2016-10-07 14:25:00
[endTime] => 2016-10-07 14:30:00
)

[4] => stdClass Object
(
[pupil_id] => 48307
[fullname] => Callum Lacey
[grade_id] => 87
[meeting_id] => 1813
[slot_id] => 31311
[title] => Parent Evening 2 - 2016-10-07 14:00
[startTime] => 2016-10-07 14:30:00
[endTime] => 2016-10-07 14:40:00
)

[5] => stdClass Object
(
[pupil_id] => 48307
[fullname] => Callum Lacey
[grade_id] => 87
[meeting_id] => 1815
[slot_id] => 31318
[title] => Parent Evening 3 - 2016-10-07 14:00
[startTime] => 2016-10-07 14:40:00
[endTime] => 2016-10-07 14:50:00
)

[6] => stdClass Object
(
[pupil_id] => 79571
[fullname] => Daniel Lacey
[grade_id] => 87
[meeting_id] => 1815
[slot_id] => 31319
[title] => Parent Evening 3 - 2016-10-07 14:00
[startTime] => 2016-10-07 14:50:00
[endTime] => 2016-10-07 15:00:00
)
)
)
)

Answer

You need to sort the array in the array in the array:

foreach($this->meetingSlotsTaken as $k1 => $v1){
    foreach($v1 as $k2 => $v2){
        usort($this->meetingSlotsTaken[$k1][$k2], 'arraySorter');
    }
}