usort没有按预期运行

时间:2016-06-08 12:02:44

标签: php sorting multidimensional-array

我有一个简单的二维数组:

$users = array(
    array('user' => 'John', 'points' => '0'),
    array('user' => 'Paul', 'points' => '0'),
    array('user' => 'George', 'points' => '0'),
    array('user' => 'Ringo', 'points' => '0')
);

我需要按points (DESC)然后按name (ASC)对它们进行排序。 这将是我的代码:

function sortByOrder($a, $b) {
    if($b['points'] == $a['points'])
        return $a['user'] - $b['user'];
    else
        return $b['points'] - $a['points'];
}

usort($users, 'sortByOrder');

我得到原始订单而不是字母顺序(因为它们目前都有0分)。为什么呢?

2 个答案:

答案 0 :(得分:1)

您需要使用array_multisort

DEMO

$users = array(
    array('user' => 'John', 'points' => '0'),
    array('user' => 'Paul', 'points' => '0'),
    array('user' => 'George', 'points' => '0'),
    array('user' => 'Ringo', 'points' => '0')
);

$sort = array();
foreach($users as $k=>$v) {
    $sort['points'][$k] = $v['points'];
    $sort['user'][$k] = $v['user'];
}

array_multisort($sort['points'], SORT_DESC, $sort['user'], SORT_ASC,$users);

print_r($users);

结果:

Array
(
    [0] => Array
        (
            [user] => George
            [points] => 0
        )

    [1] => Array
        (
            [user] => John
            [points] => 0
        )

    [2] => Array
        (
            [user] => Paul
            [points] => 0
        )

    [3] => Array
        (
            [user] => Ringo
            [points] => 0
        )

)

这个DEMO有不同的分数

答案 1 :(得分:1)

你需要使用strcmp,所以你的功能应该是这样的

function sortByOrder($a, $b) {
    if($b['points'] == $a['points'])
    {
        return strcmp($a['user'], $b['user']);
    }
    else{
        return $b['points'] - $a['points'];
    }
}

点击此处:https://eval.in/585383