<?php
function getClosestIdByAmount($amount = 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 )
);
$result_id = null;
$take_next = false;
foreach ($prices as $i => $item) {
// amount < any price of the array
if ($i === 0 && $item['price'] > $amount){
$result_id = $item['id'];
break;
} else {
if ($item['price'] < $amount) {
// amount > price1 AND amount < price2
$take_next = true;
} elseif ($item['price'] == $amount){
// amount == some price
$result_id = $item['id'];
break;
} else {
if ($take_next){
$result_id = $item['id'];
}
break;
}
}
}
return "Amount: " . $amount . " Closest ID: " . $result_id . PHP_EOL;
}
$amount = 99;
echo getClosestIdByAmount($amount);
$amount = 113;
echo getClosestIdByAmount($amount);
$amount = 115;
echo getClosestIdByAmount($amount);
$amount = 131;
echo getClosestIdByAmount($amount);
- Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- Amount: 99 Closest ID: 28
Amount: 113 Closest ID: 31
Amount: 115 Closest ID: 31
Amount: 131 Closest ID:
preferences:
77.38 ms | 407 KiB | 5 Q