0

I have an array of value series like:

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

Another value getting from DB like:

$point = $data[‘earned_point’];

I need the highest match from the series. such as I got a value from db (1500) the highest match of the value is 1000 in the series, so I need to get the $series[4] and make it

$reward = $series[4] * 0.1;

I'll run it in a loop to do it for all the values got from DB.

4
  • Please make an example from input and expected output. Commented Apr 2, 2015 at 15:50
  • What is the problem? Note that you need straight single or double quotes, no curly quotes. Commented Apr 2, 2015 at 15:51
  • $reward = $series[$point] / 10 Commented Apr 2, 2015 at 16:03
  • I need the highest match from the series. such as I got a value from db (1500) the highest match of the value is 1000 in the series, so I need to get the $series[4] and make it $reward = $series[4] * 0.1; Commented Apr 2, 2015 at 16:23

2 Answers 2

1

I'm posting alternate code as the accepted answer while is correct can be very inefficient if you are working with a large array.

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

?>
Sign up to request clarification or add additional context in comments.

Comments

0

Do you mean you want to get which highest $series item is equal or less than $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;

Let me know if this works for you

1 Comment

I need the highest match from the series. such as I got a value from db (1500) the highest match of the value is 1000 in the series, so I need to get the $series[4] and make it $reward = $series[4] * 0.1;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.