Home > Back-end >  How to find value with in range
How to find value with in range

Time:12-29

I have a table EmployeeSequence like below

id sequence_name
1 0
2 1-4
3 5-9
4 10-19
5 20-29
6 30-39
7 40-49
8 50-99
9 100-149
10 150-199
11 200-249
12 250 or above

How can find the value's range in my code below. Now when i submit the range (35), i want to find the range it belongs to so i can get the respective sequence_name.

I have some code so please clean-up.

function findSequenceInRange($sequence) {
                $employee_sequences = EmployeeSequence::all();
                $employment_range = 0;
                foreach ($employee_sequences as $employee){
                    if($employee->sequence_name > 0 && $employee->sequence_name!='250 or above'){
                        $nums = explode('-',$employee->sequence_name);
                        if($sequence >= $nums[0] && $sequence <= $nums[1]){
                            $employment_range = $employee->sequence_name;
                        }
                    }else if($sequence >= 250){
                        $employment_range = $employee->sequence_name;
                    }else if($sequence==0){
                        $employment_range = $employee->sequence_name;
                    }
                }
                
        return  $employment_range;  
    }

CodePudding user response:

You could use a groupby with callback and return the id based on sequence. As there is no overlap in the size of your ranges the best approach might be to just hardcode the if-else structure. A little prettier could be to make an array out of it e.g.

$ranges = [
    [
        'min' => 1
        'max' => 4,
    ],
    ...
];

CodePudding user response:

I'd say the cleaner way would be to change your table as to include a "min" and "max" column. This way, you'll be able to easily get the expected result with an SQL request (giving you the option to use it on your Models too)

If you do so, your request will look something like this and give you the expected result :

"SELECT * FROM sequence_table WHERE $sequence > sequence_table.min AND $sequence < sequence_table.max"

  • Related