php多列排序示例

2021-08-11 18:19  920人阅读  评论 (0)
Tags: php
<?php
// 奥运金牌排行
$scores = [
    ['name' => '美国', 'gold' => 39, 'silver' => 41, 'bronze' => 33],
    ['name' => '中国', 'gold' => 38, 'silver' => 32, 'bronze' => 18],
    ['name' => '日本', 'gold' => 27, 'silver' => 14, 'bronze' => 17],
    ['name' => '英国', 'gold' => 22, 'silver' => 21, 'bronze' => 22],
    ['name' => '俄罗斯', 'gold' => 20, 'silver' => 28, 'bronze' => 23],
    ['name' => '澳大利亚', 'gold' => 17, 'silver' => 7, 'bronze' => 22],
    ['name' => '荷兰', 'gold' => 10, 'silver' => 12, 'bronze' => 14],
    ['name' => '法国', 'gold' => 10, 'silver' => 12, 'bronze' => 11],
    ['name' => '德国', 'gold' => 10, 'silver' => 11, 'bronze' => 16],
    ['name' => '意大利', 'gold' => 10, 'silver' => 10, 'bronze' => 20],
];

shuffle($scores); // 打乱顺序

var_dump($scores);

usort($scores, function($b, $a) { // 排序
    if ($a['gold'] != $b['gold']) { // 先根据金牌
        return $a['gold'] - $b['gold'];
    }
    if ($a['silver'] != $b['silver']) { // 再根据银牌
        return $a['silver'] - $b['silver'];
    }
    return $a['bronze'] - $b['bronze']; // 最后铜牌
});

var_dump($scores);





豫ICP备09035262号-1