群组和秩算法

时间:2014-05-29 03:13:00

标签: php grouping ranking

我正在尝试根据分数分组来计算排名。

以下是数据示例,实际数据是动态的。得分越低,得分越低。

$data = array(
    array('id' => 1, 'name' => 'John Snow', 'score' => 80),
    array('id' => 2, 'name' => 'John Fire', 'score' => 50),
    array('id' => 3, 'name' => 'John Water', 'score' => 79),
    array('id' => 4, 'name' => 'John Leaf', 'score' => 80),
);

结果打印输出将是id:

ID   Name       Score Rank
1    John Snow  80    1
2    John Fire  50    3
3    John Water 79    2
4    John Leaf  80    1

谢谢!

2 个答案:

答案 0 :(得分:3)

我使用了rsort()

$data = array(
    array('id' => 1, 'name' => 'John Snow', 'score' => 80),
    array('id' => 2, 'name' => 'John Fire', 'score' => 50),
    array('id' => 3, 'name' => 'John Water', 'score' => 79),
    array('id' => 4, 'name' => 'John Leaf', 'score' => 80),
);


$score = array();
foreach ($data as $idx => $dataInd) {
    $score[$dataInd['score']] = $dataInd['score'];
}

rsort($score);

foreach ($data as $idx => $dataInd) {
    $data[$idx]['rank'] = array_search($dataInd['score'], $score) + 1; 
}

var_dump($data);

这将导致:

array (size=4)
  0 => 
    array (size=4)
      'id' => int 1
      'name' => string 'John Snow' (length=9)
      'score' => int 80
      'rank' => int 1
  1 => 
    array (size=4)
      'id' => int 2
      'name' => string 'John Fire' (length=9)
      'score' => int 50
      'rank' => int 3
  2 => 
    array (size=4)
      'id' => int 3
      'name' => string 'John Water' (length=10)
      'score' => int 79
      'rank' => int 2
  3 => 
    array (size=4)
      'id' => int 4
      'name' => string 'John Leaf' (length=9)
      'score' => int 80
      'rank' => int 1

答案 1 :(得分:2)

以下是为阵列中的每个人分配非唯一排名的代码:

$data = array(...);

// create hash map with unique scores
$scores = array();
foreach ($data as $v)
    $scores[$v['score']] = 1;

// sort by keys
krsort($scores);

// assign proper ranks to each score 
$rank = 1;
foreach ($scores as &$v)
    $v = $rank++;

// assign ranks
foreach ($data as &$v)
    $v['rank'] = $scores[$v['score']];

print_r($data);

要了解它是如何工作的,我建议您在每次操作后添加print_r($scores);以查看其中的内容