Wednesday, 29 August 2018

PHP sort the multidimensional array that contains duplicates

I am trying to sort this multi-dimensional array by rating.

Array
(
    [0] => Array
        (
            [id] => 4
            [image] => test-image.gif
            [name] => Mia Panton
            [description] => From Falkirk
Wearing: River Island
            [month] => 04-2012
            [rating] => 0.0000
            [votes] => 0
        )

    [1] => Array
        (
            [id] => 3
            [image] => test-image.gif
            [name] => Sam Jane Raggett
            [description] => From: Falkirk
Fav Shop: Republic
            [month] => 04-2012
            [rating] => 1.0000
            [votes] => 1
        )

    [2] => Array
        (
            [id] => 2
            [image] => test-image.gif
            [name] => Sasha Westbrooke
            [description] => From Falkirk
Wearing: River Island
            [month] => 04-2012
            [rating] => 4.0000
            [votes] => 2
        )

    [3] => Array
        (
            [id] => 1
            [image] => test-image.gif
            [name] => Max Rose-Collins
            [description] => From: London
Fav Shop: blah
            [month] => 04-2012
            [rating] => 3.3333
            [votes] => 6
        )

)

I am using this to do so
function orderByRating($a, $b) {
    return $a['rating'] - $b['rating'];
}
usort($array, 'orderByRating');

But as you can see it doesn't seem to work as 0 is at the top and then 1 then 4 then 3. I'm not sure if it has any thing to do with the fact the numbers are doubles?!
Any help would be appreciated. Thank you

Using Google http://www.php.net/manual/en/function.uasort.php#100325 (and slightly corrected)
function sorting($a, $b)
{
    $d = $a['rating'] - $b['rating'];
    return $d < 0 ? -1 : ($d > 0 ? 1 : 0);
}

0 comments:

Post a Comment