我有一个函数,对于特定的数字范围,必须应用百分比:
- 0-100 欧元:5%
- >100欧元:3%
此数字范围和百分比应由用户定义。
实现应尽可能简单。
您对指定范围和计算结果有什么建议?
假设您可以访问某种数据库,我会将值存储在那里。您至少需要 3 个表:
范围
- id_range
- from_number
- until_number
- 百分比
用户
- id_user
用户范围
- id_range
- id_user
使from_number和until_number列可为空,以表示 X 之前的任何内容以及 Y 之后的任何内容。
这是我使用数组中定义的规则计算结果的简短方法
$rules = array(
5 => '0-100 EUR', // here the percentages and their corresponding values
3 => '> 100 EUR'
);
$rand = mt_rand(0, 100); // calculate a random percent value
$lastPercentage = 0;
foreach($rules as $percentage => $val) {
// create a range from 0-5 (in the first iteration)
// every next iteration it is lastPercentage + 1 (5 + 1 in this case) to lastPercentage + current percentage
$range = range($lastPercentage, $percentage + $lastPercentage);
// yep, it is in the percentage range
if (in_array($rand, $range)) {
echo $lastPercentage,' < '.$rand.' > '.($percentage + $lastPercentage);
}
$lastPercentage = $percentage + 1; // +1 so that there are no overlapping ranges
}