您正在尝试将数字 17 和 38 映射到数字 1 和 5,并在其间插入所有值。让我们在下面的示例中使用这些数字,其中 num 表示范围内的任何数字:
(num - 17) maps 17 and 38 to 0 and 21
(num - 17) / (21) maps 0 and 21 to 0 and 1
(num - 17) / (21) * (4) maps 0 and 1 to 0 and 4
(num - 17) / (21) * (4) + 1 maps 0 and 4 to 1 and 5
PHP 代码:
function mapvaluetorange($array, $a, $b) {
$map = array();
$min = min($array);
$max = max($array);
foreach ($array as $value) {
$map[] = array(
"old" => $value,
"new" => ($value - $min) / ($max - $min) * ($b - $a) + $a
);
}
return $map;
}
$map = mapvaluetorange(array(34, 35, 33, 17, 38, 29, 31, 23), 1, 5);
输出:
int(34) -> float(4.2380952380952)
int(35) -> float(4.4285714285714)
int(33) -> float(4.047619047619)
int(17) -> int(1)
int(38) -> int(5)
int(29) -> float(3.2857142857143)
int(31) -> float(3.6666666666667)
int(23) -> float(2.1428571428571)
使用round 函数将浮点数舍入为整数。