开发者

PHP: Calculate differences between array values?

开发者 https://www.devze.com 2023-01-26 20:54 出处:网络
I am working on a pricing estimator, which are based on the following array: $items = 7; $margins = array(

I am working on a pricing estimator, which are based on the following array:

$items = 7;

$margins = array(
   1 => 140, // Base price
   3 => 120,
   5 => 100,
  10 => 60);

By running the following line, I get the nearest value:

$margin = $margins[max(array_intersect(array_keys($margins),range(0, $items)))];

echo $margin; // Outputs 100'

However, if this function would operate on an array with a lot of space between each value, the nearest val开发者_如何学Pythonue would be really far away from the previous, resulting in a price that's probably going to make the customer sad...

How can I get a more precise result from this - like if I had manually filled out the gaps in the margin array, to cover all potential item quantities (which surely isn't efficient)?

Thanks


You could get a list of all numbers with something like range(1, 10). Then loop through and fill the gaps :)


When you write 1 => 140, 3 => 120, 5 => 100, 10 => 60 I assume you mean "between 5 and 9, every item costs 100", so that buying 7 items costs 7x100 = 700. If that's the case, you can simply traverse the entire array once and get the resulting per-item price:

function get_price($prices,$real_qty) 
{
  foreach ($prices as $qty => $price) 
    if ($qty <= $real_qty) $real_price = $price;
    else break;
  return $real_price * $real_qty;
}

If the prices have been sorted by quantity (using ksort, for instance) then this function will return the total price for the provided quantity, doing very little work: at worst, it would look at every item in the price array once, and you probably only have a dozen or so items in that array.

On the other hand, if you think buying 7 items should cost something other than 700, then you have to explain how much it should cost and why, because it is not obvious from the problem data.

0

精彩评论

暂无评论...
验证码 换一张
取 消