I have problem with sorting this array:
Array
(
[0] => stdClass Object
(
[id] => 120
[registration_date] => 2012-10-19 16:57:46
[username] => Jeff
)
[1] => stdClass Object
(
[id] => 121
[registration_date] => 2012-12-23 16:57:46
[username] => Peter
)
[2] => stdClass Object
(
[id] => 122
[registration_date] => 2012-11-30 16:57:46
[username] => Susan
)
)
It is stored in variable:
$unsorted_users
I want to order this array DESC by registration_date so it looks like this:
Array
(
[0] => stdClass Object
(
[id] => 121
[registration_date] => 2012-12-23 16:57:46
[username] => Peter
)
[1] => stdClass Object
(
[id] => 122
[registration_date] => 2012-11-30 16:57:46
[username] => Susan
)
[2] => stdClass Object
(
[id] => 120
[registration_date] => 2012-10-19 16:57:46
[username] => Jeff
)
)
and it is ordered by registration_date like:
2012-12-23 16:57:46
2012-11-30 16:57:46
2012-10-19 16:57:46
Instead of original where it was like:
2012-10-19 16:57:46
2012-12-23 16:57:46
2012-11-30 16:57:46
I am using this code, but it is not working good (the print_r($sorted_users); output of $sorted_users is “1”. I don’t why it is 1 and not sorted array.)
$sorted_users = usort($unsorted_users, function($a, $b) {
return $a['registration_date'] - $b['registration_date'];
});
Any advice why is my code for $sorted_users wrong?
You can’t substract (that) strings. If you want to compare two strings, use the strcmp() function like this:
fiddle here