0

i have and amount to compare with the prices in the array and bring one id result.

let say the amount is 113, in this case a need to pick id 31 as result because i have to take the one closer but the biggest one or the exact one in case be like 110 or 115 using php 5.3 to 7.1

$prices = array(
  array('id' => '28','price' =>100 ),
  array('id' => '29','price' =>105 ),
  array('id' => '30','price' =>110 ),
  array('id' => '31','price' =>115 ),
  array('id' => '32','price' =>120 ),
  array('id' => '33','price' =>125 ),
  array('id' => '34','price' =>130 )
);

i search on internet i try some array function. i found this article here, but does not meet my need. text

jeyglo
  • 137
  • 1
  • 5

3 Answers3

0

The easiest way is using the next foreach loop:

$amount = 113;
$result_id = null;
$take_next = false;

foreach ($prices as $item) {
    if ($item['price'] < $amount) {
        $take_next = true;
    } elseif ($item['price'] == $amount){
        $result_id = $item['id'];
        break;
    } else {
        if ($take_next){
            $result_id = $item['id'];
        }
        break;
    }  
}

echo $result_id;

Note: the array must be ordered by amount. If amount is > 130, then result_id will be a null.

Demo

Update:

Covered case when amount is < 100.

Demo

Aksen P
  • 4,564
  • 3
  • 14
  • 27
0
usort($prices, fn($p1, $p2) => $p1['price'] <=> $p2['price']);
$result = array_values(array_filter($prices, fn($p) => $p['price'] >= 113))[0];

Note that the <=> operator is only available in PHP 7 or higher. It can be replace with:

usort($prices, fn($p1, $p2) => $p1['price'] < $p2['price'] ? -1 : ( $p1['price'] > $p2['price'] ? 1 : 0));
lukas.j
  • 6,453
  • 2
  • 5
  • 24
0

Well, to get the nearest highest for a given amount:

  • Just run a loop and check if the current price is greater than or equal to the amount.

  • Now, check if the difference between current price and amount is less than the previously recorded difference. If yes, update the result, else move ahead for the next value.

Snippet:

<?php

function getNearestHighest($prices, $amount){
    $resullt = null;
    $diff = PHP_INT_MAX;
    
    foreach($prices as $p){
        if($p['price'] >= $amount){
            if(abs($p['price'] - $amount) < $diff){
                $result = $p;
                $diff = abs($p['price'] - $amount);
            }
        }
    }
    
    if(is_null($result)) throw new \Exception("No nearest highest amount exists!");
    return $result;
}

Driver code:

<?php

try{
    print_r(getNearestHighest($prices, 113));
}catch(\Exception $e){
    // whatever you wish to do
}

Online Demo

Note: This will get the result in O(n) time and doesn't require the data set to be in a sorted state in the first place.

nice_dev
  • 17,053
  • 2
  • 21
  • 35