查找具有给定值的数组的匹配值


Find the matched value of an array with a given value

我有一个值序列数组,如:

$series = [100,300,500,800,1000,3000,5000,10000,15000,20000];

从DB获得的另一个价值:

$point = $data[‘earned_point’];

我需要系列赛中最高的一场。例如,我从db(1500)中得到一个值,该值在该系列中的最高匹配是1000,所以我需要得到$series[4]并使其成为

$reward = $series[4] * 0.1;

我将在一个循环中运行它,以便对从DB获得的所有值执行此操作。

我发布了替代代码作为可接受的答案,如果您使用的是大数组,则正确答案可能非常低效。

<?php
function computeReward($series, $point, $percent = 0.1){
    arsort($series); // sort the series in reverse so we can pass any array and the highest number will be the first because we are looking for a number lower or equal to our point
    foreach($series as $min_point){
        if($min_point <= $point){
            return $min_point * $percent; // return the min_point * the percentage, this stops the loop there for being more efficient
        }
    }
}
$series = [100,300,500,800,1000,3000,5000,10000,15000,20000];
$point = $data['earned_point'];
$reward = computeReward($series, $point);
?>

您的意思是想得到哪个最高的$series项等于或小于$point?

<?php
$series = [100,300,500,800,1000,3000,5000,10000,15000,20000];
$point = $data['earned_point'];
foreach ($series as $min_point) {
   if ($point >= $min_point) {
      $matched_min_point = $min_point;
   }
}
$reward = $matched_min_point*0.1;

让我知道这是否适用于