我有一个像这样的数组
array(
45=>5,
42=>4.9,
48=>5,
41=>4.8,
40=>4.9,
34=>4.9,
.....
)
此处索引为userid
,值为其得分。
现在我想要的是达到用户的百分位数,例如45,48的百分位数将是99而42,40,34将是97而41将是94.
我如何实现这一目标?
答案 0 :(得分:8)
示例:
<?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/>");
?>
答案 1 :(得分:1)
可以轻松完成
function procentile($arr, $percentile=0.95){
sort($arr);
return $arr[round($percentile * count($arr) - 1.0-$percentile)];
}