从反映范围的数组中选择最接近的值 [英] Picking the nearest value from an array reflecting ranges

查看:23
本文介绍了从反映范围的数组中选择最接近的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,根据订购的商品数量反映返利百分比:

I have an array that reflects rebate percentages depending on the number of items ordered:

$rebates = array(
   1 => 0,
   3 => 10,
   5 => 25,
  10 => 35)

意味着购买一两件商品,您不会获得返利;3 件以上可获得 10%,5 件以上可获得 20%,10 件以上可获得 35%,依此类推.

meaning that for one or two items, you get no rebate; for 3+ items you get 10%, for 5+ items 20%, for 10+ 35% and so on.

是否有一种优雅的单行方式来获得任意数量商品的正确返利百分比,例如 7?

Is there an elegant, one-line way to get the correct rebate percentage for an arbitrary number of items, say 7?

显然,这可以使用一个简单的循环来解决:这不是我要找的.我很感兴趣是否有一个核心数组或其他我不知道的函数可以更优雅地做到这一点.

Obviously, this can be solved using a simple loop: That's not what I'm looking for. I'm interested whether there is a core array or other function that I don't know of that can do this more elegantly.

我将奖励已接受的答案 200,但显然,我必须等待 24 小时才能做到这一点.问题解决了.

I'm going to award the accepted answer a bounty of 200, but apparently, I have to wait 24 hours until I can do that. The question is solved.

推荐答案

这是另一个,同样一点也不短.

Here's another one, again not short at all.

$percent = $rebates[max(array_intersect(array_keys($rebates),range(0,$items)))];

这个想法基本上是获得最高的键 (max),它介于 0$items 之间.

The idea is basically to get the highest key (max) which is somewhere between 0 and $items.

这篇关于从反映范围的数组中选择最接近的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆