2014-09-11 198 views
-1

嘿,我希望能有一個快速的!按照相反的順序排序關聯數組索引

我有一個數組

array(
(int) 30 => array(
    'score' => (int) 30, 
    'max_score' => (int) 40, 
    'username' => 'joeappleton', 
    'user_id' => '1' 
), 
(int) 34 => array(
    'score' => (int) 34, 
    'max_score' => (int) 40, 
    'username' => 'joeappleton', 
    'user_id' => '1' 
), 
(int) 36 => array(
    'score' => (int) 36, 
    'max_score' => (int) 40, 
    'username' => 'joeappleton', 
    'user_id' => '1' 
) 

我需要它被分類成遞減順序,由陣列的關鍵參考:

array( 
    36 => array('score' => 36, 'max_score' => 40, 'username' => 'joeappleton', 'user_id' => '1'), 
    34 => array('score' => 34, 'max_score' => 40, 'username' => 'joeappleton', 'user_id' => '1'), 
    30 => array('score' => 36, 'max_score' => 40, 'username' => 'joeappleton', 'user_id' => '1') 
); 

我試圖krsort( )但沒有歡樂,它似乎返回一個布爾。有任何想法嗎?

+0

從高到低還是從低到高? – 2014-09-11 07:48:18

+2

'krsort()'返回布爾值,但修改原始數組! – Justinas 2014-09-11 07:48:22

+1

是否有任何理由不能以降序創建數組?也就是說,你是否需要在兩種順序(升序和降序)或只有一個順序中使用它? – vernonner3voltazim 2014-09-11 07:49:28

回答

0

好的問題是,krsort(),使用傳遞引用。它對原始數組進行排序並返回一個布爾值。

我改變

return krsort($returnArray); //this returned true 

krsort($returnArray); return $returnArray;

0

我們可以在array_multisort使用,這給你想要的相同的結果!

<?php 
$people = array( 
(int) 30 => array(
'score' => (int) 30, 
'max_score' => (int) 40, 
'username' => 'joeappleton', 
'user_id' => '1' 
), 
(int) 34 => array(
'score' => (int) 34, 
'max_score' => (int) 40, 
'username' => 'joeappleton', 
'user_id' => '1' 
), 
(int) 36 => array(
'score' => (int) 36, 
'max_score' => (int) 40, 
'username' => 'joeappleton', 
'user_id' => '1' 
)); 
//var_dump($people); 

$sortArray = array(); 

foreach($people as $person){ 
foreach($person as $key=>$value){ 
    if(!isset($sortArray[$key])){ 
     $sortArray[$key] = array(); 
    } 
    $sortArray[$key][] = $value; 
} 
} 

$orderby = "score"; //change this to whatever key you want from the array 

array_multisort($sortArray[$orderby],SORT_DESC,$people); 

//var_dump($people); 
print_r($people); 
?>