多条件排序


题目

一个商品, 含有两个用于排序的参考, 一个是评分, 一个是价格, 现在要求评分高的排在前面, 如果评分相同则价格低的排在前面.

解法

可以使用usor 进行排序. 代码如下:

$arr = [
    ['score' => 6.7, 'price' => 8.5],
    ['score' => 8.4, 'price' => 5.5],
    ['score' => 7.8, 'price' => 6.5],
    ['score' => 9.5, 'price' => 8.4],
    ['score' => 9.3, 'price' => 7.1],
    ['score' => 7.0, 'price' => 4.4],
    ['score' => 8.7, 'price' => 8.8],
    ['score' => 8.6, 'price' => 9.1],
    ['score' => 8.3, 'price' => 7.4],
    ['score' => 9.0, 'price' => 8.1],
    ['score' => 9.0, 'price' => 6.9],
    ['score' => 8.8, 'price' => 5.5],
    ['score' => 6.7, 'price' => 7.5],
    ['score' => 8.2, 'price' => 6.6],
    ['score' => 7.9, 'price' => 8.2],
    ['score' => 9.7, 'price' => 5.6],
    ['score' => 8.7, 'price' => 8.1],
    ['score' => 7.2, 'price' => 9.5],
    ['score' => 9.0, 'price' => 4.5],
];

usort($arr, function($v1, $v2){
    if(bccomp($v1['score'], $v2['score'], 2) == 0){
        return $v1['price'] <=> $v2['price'];
    &#125;
    return $v2['score'] <=> $v1['score'];
&#125;);

print_r($arr);

Author: Itaken
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Itaken !
  TOC目录