本文介绍了在PHP中使用数组查找百分位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数组
array(
45=>5,
42=>4.9,
48=>5,
41=>4.8,
40=>4.9,
34=>4.9,
.....
)
这里的索引是userid
,价值是他的得分.
Here index is userid
and value is his score.
现在我想要的是为用户实现百分位数,例如45.48的百分位数将是99,42,40,34的百分位数将是97,而41的百分位数将是94.
Now what i want is to achieve percentile for on user for example percentile of 45,48 would be 99 and 42,40,34 would be 97 and 41 would be 94.
我该如何实现?
推荐答案
- 基于分数"对数组进行排序,升序
- 百分位数=(已排序数组中元素的索引)* 100/(数组中元素总数)
示例:
<?php
$array = array(
45=>5,
42=>4.9,
48=>5,
41=>4.8,
40=>4.9,
34=>4.9,
);
print("Unsorted array:<br/>");
print_r($array);
arsort($array);
print("<br/>");
print("Sorted array:<br/>");
print_r($array);
print("<br/>");
$i=0;
$total = count($array);
$percentiles = array();
$previousValue = -1;
$previousPercentile = -1;
foreach ($array as $key => $value) {
echo "\$array[$key] => $value";
if ($previousValue == $value) {
$percentile = $previousPercentile;
} else {
$percentile = 99 - $i*100/$total;
$previousPercentile = $percentile;
}
$percentiles[$key] = $percentile;
$previousValue = $value;
$i++;
}
print("Percentiles:<br/>");
print_r($percentiles);
print("<br/>");
?>
这篇关于在PHP中使用数组查找百分位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!