多条件排序 二


题目

多组类别的多个商品进行排序, 每个商品, 含有三个用于排序的参考, 一个是是否优先展示 一个是评分, 一个是价格, 现在要求优先展示排在最前面, 其次是评分高的排在前面, 如果评分相同则价格低的排在前面.

解法

可以使用array_walk进行数组遍历, 然后对每一项进行排序.

$arr = [
    'a' => [
        ['score' => 6.7, 'price' => 8.5],
    ],
    'b' => [
        ['score' => 8.4, 'price' => 5.5, 'is_show' => 1],
        ['score' => 7.8, 'price' => 6.5, 'is_show' => 1],
        ['score' => 9.5, 'price' => 8.4],
    ],
    'c' => [
        ['score' => 9.3, 'price' => 7.1],
    ],
    'd' => [
        ['score' => 7.0, 'price' => 4.4],
        ['score' => 8.7, 'price' => 8.8],
    ],
    'e' => [
        ['score' => 8.6, 'price' => 9.1],
        ['score' => 8.3, 'price' => 7.4],
        ['score' => 9.0, 'price' => 8.1],
    ],
    'f' => [
        ['score' => 9.0, 'price' => 6.9],
    ],
    'g' => [
        ['score' => 8.8, 'price' => 5.5],
        ['score' => 6.7, 'price' => 7.5],
    ],
    'h' => [
        ['score' => 8.2, 'price' => 6.6, 'is_show' => 1],
        ['score' => 7.9, 'price' => 8.2],
        ['score' => 7.1, 'price' => 7.6, 'is_show' => 1],
        ['score' => 8.7, 'price' => 8.1],
        ['score' => 7.2, 'price' => 9.5],
    ],
    'l' => [
        ['score' => 9.0, 'price' => 4.5],
    ],
];

array_walk($arr, function(&$val, $key){
    usort($val, function($v1, $v2){
        $show_u = $v2['is_show'] <=> $v1['is_show'];
        if($show_u != 0)&#123;
            return $show_u;
        &#125;
        if(bccomp($v1['score'], $v2['score'], 2) == 0)&#123;
            return $v1['price'] <=> $v2['price'];
        &#125;
        return $v2['score'] <=> $v1['score'];
    &#125;);
&#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目录