Realization Method of php to Quickly Judge What Range a Number Belongs to

  • 2021-10-25 06:05:02
  • OfStack

The need is this...

if ( $foo > 0 & & $foo < 100 ) $bar = 1;
elseif ( $foo > 99 & & $foo < 212 ) $bar = 2;
elseif ( $foo > 211 & & $foo < 324 ) $bar = 3;
elseif ( $foo > 323 & & $foo < 382 ) $bar = 4;
elseif ( $foo > 381 & & $foo < 465 ) $bar = 5;
elseif ( $foo > 464 & & $foo < 552 ) $bar = 6;
# ...

There are thousands of such rules... so the screen is full of $foo > __ & & $foo < __ $bar = __ ...

Efficiency and aesthetics are in question...

The value of the critical point is almost random... I can't think of a formula that can calculate $bar from $foo...
The idea at the moment is to split up all the rules 2... that will improve efficiency... but beauty is still a problem...
If sealed in a function... it seems really beautiful... but the efficiency is not as good as this...
Is there a perfect solution for both...?
Append... I wrote a scheme with the help of array sorting...
The efficiency is similar to that of realizing functions by oneself... still not as good as 2 points...

Method 1

Assuming that your ranges are continuous (in fact, discontinuity is easy to achieve) and there is no overlap (this is no problem), then by sorting the starting positions of the ranges, it can be easily achieved with 2 points.

$ranges = array(1, 100, 212, 324, 382, 465, 552);

Then all you have to do is find an a [i] that satisfies a [i] with a 2-point lookup in ranges < = t & & t < a [i+1].

Mode 2


<?php
function sorts($stage_data,$stage_num) {
array_push($stage_data,$stage_num);
$data = array_unique($stage_data);
//asort($data);
sort($data);
//var_dump($data);
return array_search($stage_num,$data);
}
$stage_data = array(0,26,51,76,100);
$stage_num = 16;
echo sorts($stage_data,$stage_num);
//res:1
?>

When the amount of data is large, I didn't do the test, and I don't know the best performance!


Related articles: