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

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

问题描述

我具有取决于项目的数量,反映回扣百分比数组排序

  $回扣=阵列(
   1 => 0,
   3 => 10,
   5 => 25,
  10 => 35)

这意味着一个或两个项目,你不退;为3+项目你得到10%,为5+项目20%,为10 + 35%等。

是否有一个的优雅的,单行的方式来获得正确的回扣比例为项目任意数量的,说 7

显然,这可以用一个简单的循环解决:那不是我要找的。我感兴趣是否有核心阵列或其他功能,我不知道可以做到这一点更优雅。


  

我要奖接受的答案200赏金,但显然,我必须等待24小时,直到我能做到这一点。这个问题就解决了​​。



解决方案

下面是另外一个,又不是短期的。

  $百分比= $回扣[MAX(array_intersect(array_keys($回扣),范围(0,$项目)));

这个想法基本上得到最高键(最大),这是 0 介于和 $项目

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)

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.

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.

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

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

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

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