多条件排序 三


题目

多组类别的多个商品进行排序, 每个商品, 含有两个用于排序的参考, 一个是评分(0-10分), 一个是价格.

现在要求评分按照梯队(8.0, 8.8, 9.0, 9.5)进行展示, 评分在相同梯队中则价格低的排在前面.

例如: 设置9.0分梯队, 则 9.0-9.9 都相当于是同一梯队中, 需要在这个评分中的所有商品按照价格低到高排序.

解法

代码实现:

$arr = [
    'a' => [
        ['score' => 8.9, 'price' => 8.5],
    ],
    'b' => [
        ['score' => 8.9, 'price' => 5.5, 'is_show' => 1],
        ['score' => 8.8, 'price' => 6.5, 'is_show' => 1],
        ['score' => 9.5, 'price' => 8.4],        
    ],
    'c' => [        
        ['score' => 9.3, 'price' => 7.1],
    ],
    'd' => [
        ['score' => 9.1, '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' => 9.7, 'price' => 7.5],
    ],
    'h' => [
        ['score' => 9.4, 'price' => 6.6, 'is_show' => 1],
        ['score' => 9.9, 'price' => 8.2],
        ['score' => 9.8, 'price' => 7.2],
        ['score' => 8.5, 'price' => 7.6, 'is_show' => 1],
        ['score' => 8.7, 'price' => 8.1],
        ['score' => 9.2, 'price' => 9.5],        
    ],
    'l' => [
        ['score' => 9.0, 'price' => 4.5],        
    ],
];

array_walk($arr, function(&$val, $key){
    $score_node = [8.0, 8.8, 9.0, 9.5,];
    usort($val, function($v1, $v2) use($score_node){
        $node_a = $node_b = $tmp_node = 0;
        foreach ($score_node as $nv){
            if($v1['score'] >= $nv){
                $node_a = $tmp_node;
            }
            if($v2['score'] >= $nv){
                $node_b = $tmp_node;
            }
            $tmp_node ++;
        }
        $node_cmp = $node_b <=> $node_a;
        if($node_cmp == 0)&#123;
            return $v1['price'] <=> $v2['price'];
        &#125;
        return $node_cmp;
    &#125;);
&#125;);

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目录