You need to modify the datetime strings in your $course
array in order to make them comparable in the manner that you want.
One (flexible) way to do this is to create DateTime()
objects from your datetime strings and compare those.
A quick note about datetimes: standard US format m/d/Y
uses forward slashes, and standard European format d-m-Y
uses hyphens. Your datetime strings are a mixture of both, using US-style forward slashes with European day/month/year ordering.
Therefore you'll have to take an additional step to parse each datetime string into a valid DateTime()
object before comparing.
Static method DateTime::createFromFormat()
can help in this regard. For example, given an array called $course
:
$course = [
[
'date' => '17/05/2016 00:00:00',
'reason' => 'DNA',
],
[
'date' => '10/05/2016 00:00:00',
'reason' => 'UTA',
],
[
'date' => '03/05/2016 00:00:00',
'reason' => 'DNA',
],
[
'date' => '26/04/2016 00:00:00',
'reason' => 'true',
],
[
'date' => '31/05/2016 00:00:00',
'reason' => 'true',
],
[
'date' => '24/05/2016 00:00:00',
'reason' => 'true',
],
[
'date' => '07/06/2016 00:00:00',
'reason' => 'true',
],
[
'date' => '14/06/2016 00:00:00',
'reason' => 'true',
],
];
You can then apply a callback with usort()
which converts the date
value of each comparison object into a valid DateTime()
objects before comparing them:
usort($course, function ($a, $b) {
$dateA = DateTime::createFromFormat('d/m/Y H:i:s', $a['date']);
$dateB = DateTime::createFromFormat('d/m/Y H:i:s', $b['date']);
// ascending ordering, use `<=` for descending
return $dateA >= $dateB;
});
print_r($course);
This yields:
Array
(
[0] => Array
(
[date] => 26/04/2016 00:00:00
[reason] => true
)
[1] => Array
(
[date] => 03/05/2016 00:00:00
[reason] => DNA
)
[2] => Array
(
[date] => 10/05/2016 00:00:00
[reason] => UTA
)
[3] => Array
(
[date] => 17/05/2016 00:00:00
[reason] => DNA
)
[4] => Array
(
[date] => 24/05/2016 00:00:00
[reason] => true
)
[5] => Array
(
[date] => 31/05/2016 00:00:00
[reason] => true
)
[6] => Array
(
[date] => 07/06/2016 00:00:00
[reason] => true
)
[7] => Array
(
[date] => 14/06/2016 00:00:00
[reason] => true
)
)
If your course array is very large, then there may be some overhead in creating DateTime
objects on the fly like the example above. YMMV. In this case, I'd consider mapping over the array first and create DateTime
objects for each entry, and then apply usort()
.
Note that, with a standard format datetime string, such as European d-m/Y H:i:s
, US m/d/Y H:i:s
or IS08601 Y-m-d H:i:s
, you can simply pass the datetime string as the first value into the DateTime
constructor instead; e.g:
$dt = new DateTime($someStandardFormatDateTimeString);
Apologies about the errant close vote earlier. I've removed that now.
Hope this helps :)