说我想要一组数字:
$a['a'] = 10;
$a['b'] = 20;
$a['c'] = 500;
$a['d'] = 1000;
并强制它们适合范围(例如1到100),如下所示:
$a['a'] = 1;
$a['b'] = 2;
$a['c'] = 50;
$a['d'] = 100;
另一个例子......
自:
$a['a'] = 12;
$a['b'] = 28;
要:
$a['a'] = 1;
$a['b'] = 100;
最好的方法是什么?
答案 0 :(得分:7)
的更新强> 的
现在我明白了你真正想要的东西,你需要使用这个公式:
(new_max - new_min)(x - min)
f(x) = ---------------------------- + new_min
max - min
E.g:
$a = [
'a' => 10,
'b' => 20,
'c' => 500,
'd' => 1000,
];
$min = min($a);
$max = max($a);
$new_min = 1;
$new_max = 100;
foreach ($a as $i => $v) {
$a[$i] = ((($new_max - $new_min) * ($v - $min)) / ($max - $min)) + $new_min;
}
var_dump($a);
示例:http://codepad.viper-7.com/hwGnhJ
旧回答:
您可以使用array_walk
和min
/ max
:
$a = [1, 2, 1000];
array_walk($a, function(&$value) {
$value = max(min($value, 100), 1);
});
var_dump($a);
示例:http://codepad.viper-7.com/jjOCjx
或者只是一个简单的foreach
和if
:
foreach ($a as $i => $v) {
if ($v > 100) $a[$i] = 100;
elseif ($v < 1) $a[$i] = 1;
}
答案 1 :(得分:0)
您好,您可以通过以下方式执行此操作。
$a['a'] = 10;
$a['b'] = 20;
$a['c'] = 500;
$a['d'] = 1000;
$range =10; // you can define the range here which you want.
foreach($a as $k=>$v)
{
$a[$k] = $v/$range;
}
print_r($a);