在php中使用数组查找百分位数 [英] Find percentile using an array in php

查看:29
本文介绍了在php中使用数组查找百分位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组

 array(
      45=>5,
      42=>4.9,
      48=>5,
      41=>4.8,
      40=>4.9,
      34=>4.9,
      .....
      )

这里的index是userid,value是他的分数.

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.

我如何才能做到这一点?

How i can achieve this?

推荐答案

  1. 根据分数"对数组进行排序,升序
  2. 百分位数 =(已排序数组中元素的索引)* 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中使用数组查找百分位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆