1

只需说我想获取一组数字:

$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;

最好的方法是什么?

4

2 回答 2

7

更新:

现在我明白了你真正想要什么,你需要使用这个公式:

       (new_max - new_min)(x - min)
f(x) = ----------------------------  + new_min
                max - min

例如:

$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

或者只是一个简单的foreachand if

foreach ($a as $i => $v) {
    if ($v > 100) $a[$i] = 100;
    elseif ($v < 1) $a[$i] = 1;
}
于 2012-07-23T06:10:37.873 回答
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);
于 2012-07-23T06:21:08.397 回答