简体   繁体   English

如何获得大于一定数值的数组中的最小值?

[英]How can I get the min value in an array above a certain number?

I have an array like this: 我有一个像这样的数组:

[5229561]=> 8
[5229582]=> 9
[5229583]=> 10
[5229584]=> 11
etc 等等

How can I get the minimum value greater than/equal to 10? 如何使最小值大于/等于10?

So, it this example, it would give me 5229583. I know about the min() function, but I'm not sure how to get a value greater than 10. 因此,在这个示例中,它将给我5229583。我知道min()函数,但是我不确定如何获取大于10的值。

If array is sorted and keys are consecutive(eg 100,101,102 no 78,5,13) you may use binary search. 如果数组已排序并且键是连续的(例如100,101,102否78,5,13),则可以使用二进制搜索。

Overwise you can't do it more quickly than linear search. 总的来说,您不能比线性搜索快得多。

Code with O(1) additional memory usage: 带O(1)额外内存使用量的代码:

$curbest=null;
foreach($data as $k => $v){
    if($v>=10 && (is_null($curbest) || $v<$data[$curbest]))
        $curbest=$k;
}

You need to evaluate the array for this, a number of methods you can use: 您需要为此评估数组,可以使用多种方法:

for simplicity (and not trying to be fancy) i'll show you the easiest way to learn to do this in PHP. 为了简单起见(而不是幻想),我将向您展示学习PHP的最简单方法。

$input_array = array('5229561' => 8,
                     '5229582' => 9,
                     '5229583' => 10,
                     '5229584' => 11);

foreach ($input_array as $key => $value) {
    if($value >= 10) {
        $output[$key] = $value;
    }
}

$output will be: $输出将是:

array (
      '5229583' => 10,
      '5229584' => 11
      )

hope that helps 希望能有所帮助

EDIT Addition: (Due to RiaD post below) another simple method to do this. 编辑补充:(由于下面的RiaD帖子)另一种简单的方法可以做到这一点。

function greaterTen($var) {
    return ($var >= 10);
}

$output = array_filter($input_array,"greaterTen");

and even (as of php5.3): 甚至(从php5.3开始):

$output = array_filter($input_array,function ($var) {
    return ($var >= 10);
});

You'd probably want to just sort the array (use ksort if you need the keys to stay the same) and then iterate until you find >= the minimum value. 您可能只想对数组排序(如果需要键保持不变,请使用ksort ),然后进行迭代直到找到> =最小值。

Like so: 像这样:

    function findMinValueAbove($array, $min)
    {
      sort($array); # Thanks!
      foreach ($array as $v) if ($v >= $min) return $v;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM