PHP排序包含双精度的多维数组

时间:2012-04-28 17:16:35

标签: php multidimensional-array sorting

我试图通过评级对这个多维数组进行排序。

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。 我不确定这些数字是双打的事实是否有任何关系?!

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

3 个答案:

答案 0 :(得分:4)

使用Google 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);
} 

答案 1 :(得分: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");

答案 2 :(得分:-1)

你不应该返回a-b,因为当a-b小于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);