小编The*_*igK的帖子

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

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

$user_scores = [ 82 => [ 'score' => 1, 'time' => 6.442 ],
                 34 => [ 'score' => 1, 'time' => 5.646 ],
                 66 => [ 'score' => 3, 'time' => 1.554 ]
               ]
Run Code Online (Sandbox Code Playgroud)

上面数组中的“键”是“user_ids”,我需要将其保留在排序数组中。到目前为止我最好的尝试如下 -

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

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

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

php sorting usort multidimensional-array asort

3
推荐指数
1
解决办法
4102
查看次数

标签 统计

asort ×1

multidimensional-array ×1

php ×1

sorting ×1

usort ×1