使用usort和spaceship运算符正确排序多维数组

时间:2017-06-01 13:58:14

标签: php sorting multidimensional-array usort asort

我需要使用以下逻辑对以下数组进行排序:如果'得分'相同,我想使用'时间'进行比较。数组如下:

$user_scores = [ 82 => [ 'score' => 1, 'time' => 6.442 ],
                 34 => [ 'score' => 1, 'time' => 5.646 ],
                 66 => [ 'score' => 3, 'time' => 1.554 ]
               ]

上面数组中的'keys'是'user_ids',我需要在排序数组中保留它。到目前为止,我最好的尝试如下 -

$result = usort( $user_scores, function ( $a, $b ) {
    if ( $a['score'] == $b['score'] ) {
        return $a['time'] == $b['time'];
        }
    return $a['score'] <=> $b['score'];
} );

显然,这不起作用,我得到$ user_scores数组,所有键都替换为0,1,2而不是user_ids(82,34和66)。排序也不起作用。

对于上面的数组,我想要的输出是$ user_scores array:

$user_scores = [ 34 => [ 'score' => 1, 'time' => 5.646 ],
                 82 => [ 'score' => 1, 'time' => 6.442 ],
                 66 => [ 'score' => 3, 'time' => 1.554 ]
               ]

如果您能告诉我如何使用宇宙飞船运营商(如果有意义的话)完成这项工作,我将非常感激。感谢您的时间,我期待您的回复。

---更新---

所需的排序逻辑如下:

  1. 得分越高,排名越高。
  2. 时间越长,排名越低。
  3. 它基本上是对测验结果进行排序。最少时间的得分最高的人将位于最顶层;那些得分较低,时间较长的人将处于最底层。

1 个答案:

答案 0 :(得分:1)

要保留密钥,您只需使用uasort() 我为你的回归time比较添加了一艘宇宙飞船 我改变了你回归score比较的顺序 代码中的$result只会返回true/false,因此对您没用。 sort()的功能不能分配给变量;它们直接影响输入数组。

方法:

$user_scores = [ 82 => [ 'score' => 1, 'time' => 6.442 ],
                 34 => [ 'score' => 1, 'time' => 5.646 ],
                 66 => [ 'score' => 3, 'time' => 1.554 ],
                 7 => [ 'score' => 2, 'time' => 4.442 ],
                 99 => [ 'score' => 4, 'time' => 3.646 ],
                 55 => [ 'score' => 1, 'time' => 2.554 ]
               ];

uasort($user_scores,function($a,$b){
    if($a['score'] == $b['score']){
        return $a['time'] <=> $b['time'];
    }
    return $b['score'] <=> $a['score'];
});
var_export($user_scores);

输出:

array (
  99 => 
  array (
    'score' => 4,
    'time' => 3.646,
  ),
  66 => 
  array (
    'score' => 3,
    'time' => 1.554,
  ),
  7 => 
  array (
    'score' => 2,
    'time' => 4.442,
  ),
  55 => 
  array (
    'score' => 1,
    'time' => 2.554,
  ),
  34 => 
  array (
    'score' => 1,
    'time' => 5.646,
  ),
  82 => 
  array (
    'score' => 1,
    'time' => 6.442,
  ),
)
相关问题