月度归档:2019年04月

使用usort排序的通用方法

一、问题描述
先抛出问题,有一个二维数组,有多个维度的字段,需要计算出各个维度单独的排名, 降序排列?
数据简化后如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 示例数据生成
for ($i = 0; $i < 100; $i++) {
      $data = [
          'id' => $i,
          'read_count' => mt_rand(100000, 999999),
          'interactive_count' => mt_rand(10000, 99999),
          'search_count' => mt_rand(1000, 9999),
          'video_count' => mt_rand(100, 999),
          'checkin_count' => mt_rand(100, 999),
          'watch_count' => mt_rand(100, 999),
          'score' => mt_rand(60, 90),
          'play_status' => mt_rand(1, 2),
      ];
 
      $datas[] = $data;
 }
 
// 演示例数据
function getDemoData()
{
     $datas = [
      ['id' => 1,'score' => 10, 'read_count' => 1000, 'search_count' => 90],
      ['id' => 2,'score' => 80, 'read_count' => 300, 'search_count' => 490],
      ['id' => 3,'score' => 10, 'read_count' => 500, 'search_count' => 590],
     ];
     return $datas;
}

二、直接的解发
简单粗暴的办法,你必然能想到,如下:
算法:
0、定义一个排序类,每个维度定义一个排序方法
1、对每个维度分别排一次
2、分别记录每个维度的排名
继续阅读