views:

79

answers:

2

I have the following array, I need to reorder it by average rating descending. Here is a snippet. Any idea how I would go about doing this?

Thanks

Array
(
    [0] => Array
        (
            [id] => 3
            [name] => 
            [rating] => 0
        )

    [1] => Array
        (
            [id] => 2
            [name] => 
            [rating] => 2
        )
)
+2  A: 

You can use usort() for this.

usort($arr, 'by_rating');

function by_rating($a, $b) {
  if ($a['rating'] == $b['rating']) {
    return 0;
  } else {
    return $a['rating'] < $b['rating'] ? -1 : 1;
  }
}

Or in reverse:

function by_rating($a, $b) {
  if ($a['rating'] == $b['rating']) {
    return 0;
  } else {
    return $a['rating'] < $b['rating'] ? 1 : -1;
  }
}
cletus
Thanks, I knew there must be something like this floating around.
JasonS
+1  A: 

Use PHP's usort() function (docs here). You can supply your own callback function which is called with 2 inputs. You can carry out whatever comparison you like in the function and return whichever value you think is best etc:

function myComparison($val1, $val2)
{
  if ($val1["rating"] == $val2["rating"])
  {
    return 0;
  }
  return ($val1["rating"] < $val2["rating"]) ? -1 : 1;  
}

usort($inputArray, "myComparison");

(example from the PHP site, adopted for your result set above).

richsage