#1
  1. No Profile Picture
    Coopercentral
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2002
    Location
    Rochester, NY
    Posts
    24
    Rep Power
    0

    Sorting an array by key/value


    Hi:

    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:

    Choice1
    Choice2
    Choice3
    Choice4

    But, with "Choice2" having 1 vote, it would show:

    Choice2
    Choice1
    Chioce3
    Choice4

    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?
  2. #2
  3. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,317
    Rep Power
    7170
    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:
    PHP Code:
    array(
      array(
        
    'choice' => 1,
        
    'votes' => 0,
      ),
      array(
        
    'choice' => 2,
        
    'votes' => 1,
      ),

    Your comparison function would just need to take into account both subindexes.
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around

IMN logo majestic logo threadwatch logo seochat tools logo