Find percentile using an array in php

送分小仙女□ 提交于 2019-12-05 11:43:58
  1. Sort the array based on the "score", ascending
  2. Percentile = (Index of an element in the sorted array ) * 100 / (total elements in the array)

Example:

<?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/>");

?>

It can be done a lot easier

function procentile($arr, $percentile=0.95){
    sort($arr);
    return $arr[round($percentile * count($arr) - 1.0-$percentile)];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!