2

我想根据最终分数对这个数组进行排序,并保留我的键。我可以使用 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
    )
)
4

2 回答 2

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 向上推

于 2013-06-13T07:52:35.340 回答
4

所有你需要的是

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

或者

// Descending
usort($data, function ($a, $b) {
    return $b['finalScore'] - $a['finalScore'];
});
于 2013-06-13T07:54:04.873 回答