February 16th, 2013, 11:21 AM
Sorting an array by key/value
For my poll I put the results into an array, such as this:
[Choice1] => "0",
[Choice2] => "1",
[Choice3] => "0",
[Choice4] => "0"
The key is the choice and the value is the number of votes. Basically, when the results show, I want to order by the number of votes (most at the top) but then also keep the same sort. For example, if there were NO VOTES, it would show in this order:
But, with "Choice2" having 1 vote, it would show:
I asked this years ago, but absolutely was not able to find it. Possibly it was through a private message. I could have sworn someone created a custom "usort" function. Would someone be able to help me out with this?
February 16th, 2013, 12:07 PM
What you're looking for is called a stable sort. PHP's standard array sorting functions use an unstable implementation of quicksort, so those won't work as you've found.
You could accomplish this using array_multisort, by sorting by both the value and the key.
With the data structure you have now you could not do this with any of the u*sort functions, but if you modified the data structure and added another dimension so that it looked like the following then you could:
Your comparison function would just need to take into account both subindexes.
'choice' => 1,
'votes' => 0,
'choice' => 2,
'votes' => 1,