0

I have an array that I'm simply trying to order by a score key that contains the value that I'm trying to sort by. The desired results would change the order of the array below to display the index in the following order: [0], [2], [1].

I'm looping through the results which are pulled from a database. I'm creating a key named score and then pushing the $row2 array in to a separate array because if I use mysql_data_seek it gets rid of the score key.

Also it's creating an unwanted key score at the bottom.

How can I best clean this up and make sure the results are ordered high to low as desired?

$my_array = array();

while ($row2 = mysql_fetch_assoc($result2))
{
 //score determined here
 //$row2['score'] = ...more math, variable is numeric, not a string
 array_push($array_page,$row2);
}

Current undesired results...

Array
(
    [0] => Array
        (
            [score] => 7
        )
    [1] => Array
        (
            [score] => 2
        )
    [2] => Array
        (
            [score] => 4
        )
    [score] => 
)

Desired results...

Array
(
    [0] => Array
        (
            [score] => 7
        )
    [2] => Array
        (
            [score] => 4
        )
    [1] => Array
        (
            [score] => 2
        )
)
4
  • 1
    Use order by score in your query.
    – jordanm
    Aug 26, 2012 at 5:23
  • I'm not processing the score in the SQL query. >__>
    – John
    Aug 26, 2012 at 5:24
  • ... But you're getting the score using a SQL query, right? Let the database do all the work for you.
    – EthanB
    Aug 26, 2012 at 6:05
  • No, this is all processed by PHP. Even if I could do this with MySQL I'll be migrating away from MySQL to PostgreSQL to avoid dealing with Oracle's politics so the last thing I want to do is create overly complex SQL statements.
    – John
    Aug 26, 2012 at 9:07

1 Answer 1

1
function scoreSort($a, $b){
  if($a['score'] == $b['score']) return 0;
  return $a['score'] > $b['score'] ? -1 : 1;
}
usort(&$myArray, 'scoreSort');

on php>5.3 you can use inline-functoins:

usort(&$myArray, function($a,$b){ /* ... */ });
3
  • to maintain the KEYS while sorting, please use "uksort"
    – TheHe
    Aug 26, 2012 at 5:26
  • This looks ALMOST good enough for me to accept only that it sorted the opposite way with the heaviest scores at the bottom instead of at the top where I need them. I could reverse the array though is there a simpler modification to your function that I could use please? I tried the more obvious part of changing the minus operator to plus though that didn't work.
    – John
    Aug 26, 2012 at 5:38
  • changed ;) just replace the "<" with ">" :D
    – TheHe
    Aug 26, 2012 at 5:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.