猿问

PHP 为编号变量查找最接近的百分位数

我计算了 3 个百分位值,这些值存储在这样的变量中:


$twentyfive = '55';

$fifty = '80';

$seventyfive = '95';

我网站上的每个用户都有一个 20-100 存储在变量中的值:$percentile,我试图匹配他们最接近上述三个变量之一的数字,所以我可以说:你是 X 百分位数的一部分。


例如,如果用户 $percentile 值是 '35',他们将与 $twentyfive 匹配,因为这是与他们的数字最接近的变量。


任何帮助,将不胜感激


慕斯王
浏览 139回答 3
3回答

RISEBY

如果 3 个变量的值可以更改,您可以使用它。可能有更简洁的方法,但这应该有效。//Set users percentile$user_percentile = 35;$user_percentile_category = 25;switch ($user_percentile) {&nbsp; &nbsp; case $user_percentile <= $twentyfive:&nbsp; &nbsp; &nbsp; &nbsp; $user_percentile_category = '25';&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; case ($user_percentile - $twentyfive) < $fifty - $user_percentile:&nbsp; &nbsp; &nbsp; &nbsp; $user_percentile_category = '25';&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; case ($user_percentile - $twentyfive) >= $fifty - $user_percentile:&nbsp; &nbsp; &nbsp; &nbsp; $user_percentile_category = '50';&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; case ($user_percentile - $fifty) < $seventyfive - $user_percentile:&nbsp; &nbsp; &nbsp; &nbsp; $user_percentile_category = '50';&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; case ($user_percentile - $fifty) >= $seventyfive - $user_percentile:&nbsp; &nbsp; &nbsp; &nbsp; $user_percentile_category = '75';&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; $user_percentile_category = '75';}

呼啦一阵风

您可以使用以下代码:function getClosest($search, $arr) {&nbsp; &nbsp;$closest = null;&nbsp; &nbsp;foreach ($arr as $item) {&nbsp; &nbsp; &nbsp; if ($closest === null || abs($search - $closest) > abs($item - $search)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$closest = $item;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}&nbsp; &nbsp;return $closest;}$collection = [55,80,95];$searchValue = 88;echo getClosest($searchValue, $collection);

肥皂起泡泡

if($percentile < 67.5){&nbsp; &nbsp;echo $twentyfive}&nbsp; elseif($percentile > 67.5 && $percentile < 87.7){&nbsp; &nbsp;echo $fifty}else{&nbsp; &nbsp;echo $seventyfive}
随时随地看视频慕课网APP
我要回答