-2

I have a simple two-dimensional array:

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

I need to sort them by points (DESC) and then by name (ASC). This would be my code:

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

usort($users, 'sortByOrder');

I get the original order instead of an alphabetical order (since they all have 0 points currently). Why?

castis
  • 8,154
  • 4
  • 41
  • 63
fishmong3r
  • 1,414
  • 4
  • 24
  • 51

2 Answers2

1

You need to use 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);

Result:

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
        )

)

And this DEMO with different points

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
1

You need to use strcmp, So your function should look like this

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

Check here: https://eval.in/585383

Alok Patel
  • 7,842
  • 5
  • 31
  • 47