2016-06-08 114 views
-2

我有一個簡單的二維數組:usort並不像預期的那樣

$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點目前)。爲什麼?

+0

用戶不是可數。檢查返回的布爾值。 –

+1

什麼是約翰減去保羅?或者'Ringo'減去'George'? –

回答

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

您需要使用strcmp,所以你的函數的n應像這裏這樣

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

相關問題