I have an array such as:
Array
(
[0] => Array
(
[id] => 2
[type] => comment
[text] => hey
[datetime] => 2010-05-15 11:29:45
)
[1] => Array
(
[id] => 3
[type] => status
[text] => oi
[datetime] => 2010-05-26 15:59:53
)
[2] => Array
(
[id] => 4
[type] => status
[text] => yeww
[datetime] => 2010-05-26 16:04:24
)
)
Can anyone suggest a way to sort/order this based on the datetime element?
This should work. I converted the date to unix time via strtotime.
For
'd/m/Y'
dates:where
$i
is the array indexUse
usort()
and a custom comparison function:EDIT: Your data is organized in an array of arrays. To better distinguish those, let's call the inner arrays (data) records, so that your data really is an array of records.
usort
will pass two of these records to the given comparison functiondate_compare()
at a a time.date_compare
then extracts the"datetime"
field of each record as a UNIX timestamp (an integer), and returns the difference, so that the result will be0
if both dates are equal, a positive number if the first one ($a
) is larger or a negative value if the second argument ($b
) is larger.usort()
uses this information to sort the array.Sorting array of records/assoc_arrays by specified mysql datetime field and by order:
I came across to this post but I wanted to sort by time when returning the items inside my class and I got an error.
So I research the php.net website and end up doing this:
You can find very useful examples in the PHP.net website
My array looked like this:
From php7 you can use the Spaceship operator: