在php中按降序排序数组值

时间:2013-10-31 11:23:17

标签: php arrays sorting

我的数组采用这种格式

Array
(
    [0] => 1,3
    [1] => 2,0
    [2] => 5,2
    [3] => 28,1
    [4] => 30,2
    [5] => 33,0
    [6] => 36,0
    [7] => 38,0
    [8] => 39,0
    [9] => 40,0
    [10] => 42,2
    [11] => 45,6
    [12] => 56,1
    [13] => 58,1
    [14] => 68,0
    [15] => 70,0
    [16] => 71,0
    [17] => 75,0
    [18] => 76,0
    [19] => 77,0
    [20] => 78,0
    [21] => 83,1
    [22] => 86,0
    [23] => 87,2
    [24] => 88,0
    [25] => 89,0
    [26] => 91,0
)

我希望以降序对数组进行排序,例如:array [10]中的值=> 45,6。想根据第二个值排序,即数组中的6

2 个答案:

答案 0 :(得分:6)

排序时可以使用用户定义的函数。这将做你需要它做的事。

function cmp($a, $b)
{
    $aa = explode(',', $a)[1];
    $bb = explode(',', $b)[1];
    if ($aa == $bb) {
        return 0;
    }
    return ($aa > $bb) ? -1 : 1;
}

usort($array, 'cmp');

答案 1 :(得分:2)

usort是你的朋友:

usort($array, function($a, $b){

  return explode(',', $b)[1] - explode(',', $a)[1];

});