用php设置float数组中的min值

时间:2016-05-02 10:38:51

标签: php arrays

我有一个像下面这样的php数组

array [0 => 1.0, 1 => 1.5, 2 => 3.0, 3 => 5.0, 4 => 7.5, 5 => 10.0, 6 => 20.0, 7 => 30.0, 8 => 50.0, 9 => 100.0]

我计算了类似' 6'的值。我想要做的是找到我的表的最接近的值(在这种情况下将是5)并创建一个新的数组,其中最小值为5,这将是这个

array [0 => 5.0, 1 => 7.5, 2 => 10.0, 3 => 20.0, 4 => 30.0, 5 => 50.0, 6 => 100.0]

这可能吗?

3 个答案:

答案 0 :(得分:1)

这取决于您对最接近的定义,但这里有一个可能的解决方案(假设最接近意味着数字之间的数学差异最小):

<?php
$number = 6; // this is your pre-determined number
foreach ($array as $value) {
    if (isset($temp)) {
        if (abs($number - $value) <= abs($number - $temp)) {
            $temp = $value;
        }
    } else {
        $temp = $value;
    }
}
foreach ($array as $value) {
    if ($value >= $temp) {
        $result[] = $value;
    }
}
?>

编辑:这是在假设你的初始阵列不一定要被排序的情况下编写的,并且密钥不一定是连续的。

答案 1 :(得分:1)

使用array_slice重建数组

$array  =[1.0, 1.5, 3.0,  5.0,  7.5,  10.0,  20.0,  30.0,  50.0,  100.0];

$find = 6;
// init valuse with the 1st array item
$pos = 0;
$min = abs($array[0]-$find);
for($i = 1; $i < count($array); $i++) {
   // because array is sorted we can stop iteration 
   // when abs($array[$i]-$find) begin increase
   if(abs($array[$i]-$find) > $min) break;
   // else save position and value
   else { $min = abs($array[$i]-$find); $pos = $i; }
}   

echo "Closest value : ". $array[$pos] . "\n";
$result = array_slice($array, $pos);

demo

答案 2 :(得分:1)

试试这个:

    <?php
    $arr = [0 => 1.0, 1 => 1.5, 2 => 3.0, 3 => 5.0, 4 => 7.5, 5 => 10.0, 6 => 20.0, 7 => 30.0, 8 => 50.0, 9 => 100.0];

    var_dump( getNearestSequence($arr, 6) );

    function getNearestSequence($arr, $cue){
        $nextArray  = $arr;
        $arrOffsets = array();

        foreach($arr as $iKey=>$fVal){
            $arrOffsets[] = abs( doubleval($fVal - doubleval($cue)) ) . "";
        }

        $minVal     = min($arrOffsets);
        $arrOffFlip = array_flip($arrOffsets);
        $key        = $arrOffFlip[$minVal];
        array_splice($nextArray, 0, $key);
        return $nextArray;
    }

    // SINCE 5 IS CLOSEST TO 6 ON THE SEQUENCE; THIS DUMPS:   
        array (size=7)
          0 => float 5
          1 => float 7.5
          2 => float 10
          3 => float 20
          4 => float 30
          5 => float 50
          6 => float 100