2

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)?

Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
  • arsort and see [Sorting Arrays](http://php.net/manual/en/array.sorting.php) –  Feb 18 '13 at 12:49

4 Answers4

2

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:

array( 
  array( 
    'answer' => 1, 
    'votes' => 0, 
  ), 
  array( 
    'answer' => 2, 
    'votes' => 1, 
  ), 
) 

So essentially the comparison function would just need to take into account both sub-indexes.

hope that helps

Niko
  • 26,516
  • 9
  • 93
  • 110
Craig Taub
  • 4,169
  • 1
  • 19
  • 25
  • +1 for mentioning unstability of PHP sorting functions. Actually it should also be possible without modifying the data structure, if `array_multisort` gets a variable with the `array_keys` as second parameter. – Fabian Schmengler Feb 18 '13 at 12:53
  • i appreciate this help with the logic alot, thanks –  Feb 18 '13 at 12:57
1

You want the php function "asort":

http://uk.php.net/manual/en/function.asort.php

it sorts the array, maintaining the index associations.

I've just noticed you're using a standard array (non-associative). if you're not fussed about preserving index associations, use sort( ):

http://uk.php.net/manual/en/function.sort.php

Vineet1982
  • 7,730
  • 4
  • 32
  • 67
-1

Looks like I misread the question.

asort() will sort the array by value, so the highest votes will be first in the array. thus the result will be:

[Answer2] => "1",
[Answer1] => "0",
[Answer3] => "0",
[Answer4] => "0"

or an even more complete example

[Answer2] => "42",
[Answer3] => "29",
[Answer1] => "18",
[Answer4] => "9"

Husman
  • 6,819
  • 9
  • 29
  • 47
-1

I think asort() will work..

asort($your_array);
Php Geek
  • 1,107
  • 1
  • 15
  • 36