php - 使用 fromRange 和 toRange 映射值?
我试图弄清楚如何将 1 到 1000 之间的数字映射到 1 到 5 之间的数字。
例如:
我有一个包含 1000 条记录的数据库,我想为每条记录分配一个 1 到 5 之间的 id 号。我不希望它是随机的,使用 rand(1,5)
就足够简单了。
在Arduino语言中,它有一个我希望PHP有的功能:
result = map(value, fromLow, fromHigh, toLow, toHigh)
这样做的目的是我不想将映射值存储在数据库中,我需要一个可以调用的php函数,如果说db记录的话是 100 无论函数被调用多少次,它总是返回相同的映射值。
谢谢!
I'm trying to figure out how to map a number between 1 and 1000 to a number between 1 and 5.
For example:
I have a database of 1000 records and I want to assign an id number between 1 and 5 to each record. I don't want it to be random, thats easy enough with rand(1,5)
.
In the Arduino language it has a function that I'm hoping PHP has:
result = map(value, fromLow, fromHigh, toLow, toHigh)
The purpose of this is I don't want to store that mapped value in the database, I need a php function that I can call and if say the db record is 100 no matter how often the function is called it will always return the same mapped value.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在寻找的函数通过使用不同的比例来绘制范围。所以这很容易做到:
基本上,它会在范围内重新确定数字的基数。现在,请注意,如果值在任一范围内,则不会进行错误检查。原因是它映射的是比例,而不是范围。因此,您可以使用它进行基数转换:
您也可以映射“范围”,因为它重新设置数字的基数(沿数轴移动它):
因此对于 from range (0, 1000) 和 to range (0, 5 ),下表将成立:
为了显示重新定位,如果我们将 (0, 1000) 映射到 (5, 10):
The function you're looking for maps ranges by using different scales. So that's easy to do:
So basically, it'll re-base the number within the range. Now, note that there is no error checking if value is within either range. The reason is that it maps scales, not ranges. So you can use it for base conversion:
And you can map "ranges" as well since it re-bases the number (moves it along the number line):
So for from range (0, 1000) and to range (0, 5), the following table will hold true:
And to show the re-basing, if we map (0, 1000) to (5, 10):
您是否考虑过:
$mappedValue = ($value % 5) + 1;
?将返回该值除以 5(即 0-4)后的余数,然后加一。Have you considered:
$mappedValue = ($value % 5) + 1;
? Will return the remainder after dividing the value by 5 (i.e. 0-4) then adds one.