I have a poll on my website. For it I put the results into an array such as this:
[Answer1] => "0",
[Answer2] => "1",
[Answer3] => "0",
[Answer4] => "0"
The choice is the key and the number of votes is the value. Essentially when the results show I want to order by the number of votes and then also keep the same sort. So if no votes it would show in the order:
Answer1
Answer2
Answer3
Answer4
But, with “Answer2” having 1 vote it would show:
Answer2
Answer1
Answer3
Answer4
I have tried creating a custom usort function but am having no luck.
Can anybody help me with the logic how to do it please (i can do the PHP myself)?
As you are using an associative array what you are looking for is called a stable sort.
PHP’s standard array sorting functions use an unstable implementation of quicksort so as you have found they will not help you here.
You could accomplish this though using
array_multisort. By sorting by BOTH the value and the key.With your data structure you currently have 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:
So essentially the comparison function would just need to take into account both sub-indexes.
hope that helps