将assoc数组索引按相反顺序排序


Sort an assoc array index into reverse order

嘿,伙计们,我希望一个非常快的!

我有一个阵列

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(),但没有任何乐趣,它似乎返回了一个bool。有什么想法吗?

好的,问题是krsort()使用了pass-by-reference。它对原始数组进行排序并返回一个bool。

我更改了

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

krsort($returnArray); return $returnArray;

我们可以使用array_multissort,它可以得到您想要的相同结果!!!

<?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);
?>