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

时间:2015-04-02 15:47:47

标签: php

我有一系列价值系列,如:

$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获取所有值。

2 个答案:

答案 0 :(得分:1)

如果您正在使用大型数组,那么在正确的情况下发布备用代码作为已接受的答案可能会非常低效。

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

?>

答案 1 :(得分:0)

你的意思是你想得到哪个最高的$系列项目等于或小于$ 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;

如果这对您有用,请告诉我