本文介绍了PHP的平均排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Excel中,有一个函数平均排名"(请参阅文档).

In Excel there's a function Rank Average (see documentation).

我希望在PHP中也做同样的事情.从网上看,我发现了很多排名解决方案,但是其中很多解决方案都没有考虑重复项,而当这样做时,我得到的结果与Excel给我的完全不一样.不过,这非常重要.

I wish to do the same in PHP. Looking online, I find a lot of ranking solutions, but not a lot of those take duplicates into account and when they do, the result I get is not the same as Excel is giving me at all. It's very important it does though.

理想情况下,我需要的是一个函数,该函数需要一个分数和一个数组才能与之进行比较,并为我提供排名.

Ideally, what I'd need is a function that requires a score and array to compare it with, and give me the rank for it.

带有Excel实际日期的示例:

Example with some actual date from Excel:

$array = array(5.80,6.00,6.00,5.60,3.20,3.00,3.60,5.70,3.60,1.90,5.00,5.80,3.00,3.80,5.00,3.00,6.00,5.70,5.00,4.90,4.20,3.60,5.00,4.90,4.90,3.00
3.30,4.80,4.60,4.10,4.70,6.00,3.30,4.30,4.30,3.00,3.10,6.00,1.90,3.80,5.00,2.00,2.80,3.00,4.20,3.00,5.50,6.00,5.00,5.00);

$score1 = 5.80;
$score2 = 6.00;

$rank1 = rankAvg($score1, $array); //should return 7.5
$rank2 = rankAvg($score2, $array); //should return 3.5

推荐答案

function rank_avg($value, $array, $order = 0) {
// sort
  if ($order) sort ($array); else rsort($array);
// add item for counting from 1 but 0
  array_unshift($array, $value+1);
// select all indexes vith the value
  $keys = array_keys($array, $value);
  if (count($keys) == 0) return NULL;
// calculate the rank
  return array_sum($keys) / count($keys);
}

echo rank_avg(25, array(20,23,25,27,29), 1);

这篇关于PHP的平均排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 14:37