嘿伙计们,我希望能快一点!
我有一个数组
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 :(得分:0)
好的问题是krsort()使用pass by reference。它对原始数组进行排序并返回一个bool。
我改变了
return krsort($returnArray); //this returned true
到
krsort($returnArray);
return $returnArray;
答案 1 :(得分: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);
?>