I have an associative array:
Array(
[110] => Array
(
[releaseDate] => 2020-08-15 00:00:00
[isNewest] =>
)
[128] => Array
(
[releaseDate] => 2020-08-01 00:00:00
[isNewest] =>
)
[129] => Array
(
[releaseDate] => 2020-08-01 00:00:00
[isNewest] =>
)
[130] => Array
(
[releaseDate] => 2020-08-01 00:00:00
[isNewest] =>
)
[132] => Array
(
[releaseDate] => 2020-08-01 00:00:00
[isNewest] =>
)
[123] => Array
(
[releaseDate] => 2020-07-01 00:00:00
[isNewest] =>
)
[124] => Array
(
[releaseDate] => 2020-07-01 00:00:00
[isNewest] =>
)
[125] => Array
(
[releaseDate] => 2020-07-01 00:00:00
[isNewest] =>
)
[127] => Array
(
[releaseDate] => 2020-07-01 00:00:00
[isNewest] =>
)
)
Generally this should be sorted by releaseDate
but the elements for which isNewest
is true should come first.
I use uasort()
to accomplish that:
uasort($arr, function($a, $b){
return $a['isNewest'] - $b['isNewest'];
});
Sometimes isNewest
will be true but in this example (and in the data conditions i first discovered this bug) isNewest
is false
for all entries.
Running the above, this is the result:
Array
(
[124] => Array
(
[releaseDate] => 2020-07-01 00:00:00
[isNewest] =>
)
[125] => Array
(
[releaseDate] => 2020-07-01 00:00:00
[isNewest] =>
)
[127] => Array
(
[releaseDate] => 2020-07-01 00:00:00
[isNewest] =>
)
[123] => Array
(
[releaseDate] => 2020-07-01 00:00:00
[isNewest] =>
)
[132] => Array
(
[releaseDate] => 2020-08-01 00:00:00
[isNewest] =>
)
[128] => Array
(
[releaseDate] => 2020-08-01 00:00:00
[isNewest] =>
)
[129] => Array
(
[releaseDate] => 2020-08-01 00:00:00
[isNewest] =>
)
[130] => Array
(
[releaseDate] => 2020-08-01 00:00:00
[isNewest] =>
)
[110] => Array
(
[releaseDate] => 2020-08-15 00:00:00
[isNewest] =>
)
)
The problem is that sorting the array the way i do it, using uasort()
seems to reverse the array order. If you look at the above two arrays and check the releaseDate
, you will see what i mean.
If isNewest
were true for any entries, they'd come first, but the rest of the array order would still end up being reversed.
I seem to have some trouble understanding how the uasort()
comparison function works. I tried returning -1
and 1
and even flipped the $a
and $b
parameters, but to no avail.
What am i doing wrong here? How can i use uasort()
properly here, so that the array remains sorted by releaseDate
in descending order, but in such a way that entries that have isNewest
set to true
come first?
Thank You!