2

我正在尝试按评级对这个多维数组进行排序。

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
        )

)

我正在使用它来这样做

function orderByRating($a, $b) {
    return $a['rating'] - $b['rating'];
}
usort($array, 'orderByRating');

但是正如您所看到的,它似乎不起作用,因为 0 在顶部,然后是 1,然后是 4,然后是 3。我不确定这是否与数字是双倍的事实有关?!

任何帮助,将不胜感激。谢谢

4

3 回答 3

4

使用谷歌http://www.php.net/manual/en/function.uasort.php#100325(并略有修正)

function sorting($a, $b)
{
    $d = $a['rating'] - $b['rating'];
    return $d < 0 ? -1 : ($d > 0 ? 1 : 0);
} 
于 2012-04-28T17:21:56.203 回答
0

另一种方法:
由 Lohoris 发布 (http://stackoverflow.com/a/2699110/1363184)

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

aasort($test,"rating");
于 2012-04-28T17:49:08.637 回答
-1

您不应该返回 ab,因为当 ab 小于 0 时,它会平等对待。

例如,请查看此代码。

<?php
$array = array(1.0,2.9,3.5,4.3);
function orderByRating($a, $b) {
    return $a - $b;
}
function orderByRating2($a, $b) {
    if($a>$b)
        return 1;
    if($a<$b)
        return -0;
    return 0;
}
usort($array, 'orderByRating'); // 1,3.5,2.9,4.3
usort($array, 'orderByRating2'); //1,2.9,3.5,4.3

print_r($array);
于 2012-04-28T17:22:40.883 回答