2014-09-11 65 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); 
?>