I’m sorting an associative arrays date properties (unix timestamps) using usort(). It’s working as intented. But I would like extend the functionality a bit (if possible). All the dates which are > “now” should be in the reverse order. In other words, I want the date closest to “now” to be on top of the list. Please let me know if I need to elaborate anything. My current code:
usort($DTO, function($a, $b) {
return $b['date'] - $a['date'];
});
Thank goodness you’re using PHP 5.3 or better, doing this without first-class anonymous functions would have been a pain.
Your sort should look something like this. I’ve replaced your variables with some sample data to demonstrate how it works.
I could interpret your request in two ways. I’ll provide examples for both.
The test results in:
Dates greater than “now” are at the top. They are sorted in ascending order, meaning as you go down the list, you go further into the future. When that section of the list is completed and you hit the past again, the descending sort returns, with newer dates higher than lower dates.
However, it’s also possible to interpret your request as “I don’t care about splitting the past from the future, I just want closest to now at the top.” That’s easier. We’ll break out
absto get the absolute difference between the numbers.results in
Now (5) is at the top. As you go further down the list, the absolute difference between now and then increases, mixing both past and future dates.
If neither of these interpretations is what you meant, you’ll need to clarify your question.