I have a large array and would like to find between which array开发者_如何学Go values the search value would appear.
A simplified version of this array is as follows:
[0] => Array
(
[min] => 0
[max] => 4.999
[val] => low
)
[1] => Array
(
[min] => 5
[max] => 9.999
[val] => med
)
[2] => Array
(
[min] => 10
[max] => 14.999
[val] => high
)
So if I was to search for 6.2 the returned result would be the array value 'med'
Is there a built in function that can easily walk over the array to make this calculation or would I need to set up a foreach loop
Thanks in advance
I think a simple foreach would be fast enough, with some precaution in floating point comparisons : see it here : http://codepad.org/sZkDJJQb
<?php
$rangeArray = array(
array( 'min' => 0, 'max' => 4.999, 'val' => 'low'),
array( 'min' => 5, 'max' => 9.999, 'val' => 'med'),
array( 'min' => 10, 'max' => 14.999, 'val' => 'high'),
);
$input = 6.2;
$precision = 0.00001 ;
foreach($rangeArray as $current)
{
if( ($input - $current['min']) > $precision and ($input - $current['max']) <= $precision )
{
echo $current['val'];
break;
}
}
?>
精彩评论