我可以使用基于值的usort在php中对数组进行排序

时间:2013-06-13 07:50:25

标签: php

我想根据最终得分对这个数组数组进行排序,并保留我的键。我可以使用usort吗?怎么样?

Array
(
[2253472] => Array
    (
        [noOfDays] => 1
        [bestAns] => 1
        [finalScore] => 13.5
    )

[2253465] => Array
    (
        [noOfDays] => 1
        [bestAns] => 0
        [finalScore] => 50
    )

[2253473] => Array
    (
        [noOfDays] => 1
        [bestAns] => 0
        [finalScore] => 23
    )

[2253471] => Array
    (
        [noOfDays] => 1
        [bestAns] => 0
        [finalScore] => 89
    )

[2253464] => Array
    (
        [noOfDays] => 1
        [bestAns] => 1
        [finalScore] => 0.5
    )

[2253415] => Array
    (
        [noOfDays] => 6
        [bestAns] => 0
        [finalScore] => 0.333
    )
)

2 个答案:

答案 0 :(得分:4)

是的,如果不保留密钥,您只需要用户定义的比较方法。

使用uasort()进行密钥保存:http://www.php.net/manual/en/function.uasort.php

示例:

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

uasort($a, "cmp");

对于您的阵列,有一些解释

uasort($array, "cmp");

function cmp($a,$b){
   if ($a['finalScore'] == $b['finalScore'])
    {
        // Same score, keep same
        return 0;
    }
    elseif ($a['finalScore'] > $b['finalScore'])
    {
        // $a has higher score, move $b down array
        return -1;
    }
    else {
        // $a has lower score, move $b up array             
        return 1;
    }
}

-1将其向下移动,0离开它,1向上移动

答案 1 :(得分:4)

你需要的只是

// Ascending
usort($data, function ($a, $b) {
    return $a['finalScore'] - $b['finalScore'];
});

OR

// Descending
usort($data, function ($a, $b) {
    return $b['finalScore'] - $a['finalScore'];
});