2014-11-15 57 views
0

我有一個數組,看起來像這樣的範圍:確定值是否在數組

[age-pref] => Array 
     (
      [0] => 31-35 
     ) 

我確定如果一個學生的年齡在這個範圍內這樣的:

$search_age = $filters['age-pref']; 

list($age_from, $age_to) = explode('-', $search_age[0]); 
if(!empty($age_from) && !empty($age_to)){ 
    $result_age = ($student_field['student_age'][0] >= $age_from && $student_field['student_age'][0] <= $age_to) ? true : false; 
}else{ 
    $result_age = true; 
}//endif 

$student_field['student_age'][0]是年齡。但是,如果陣列看起來像這樣:

[age-pref] => Array 
     (
      [0] => 31-35,36-40 
     ) 

我很難比較它們。有人可以用這裏的邏輯來幫忙嗎?

謝謝!

回答

1
function isAgeInRange($age, $ranges) { 
    if (empty($ranges)) return true; 
    foreach (explode(',', $ranges) as $range) { 
     $range = trim($range); 
     list($from, $to) = explode('-', $range); 
     if ($age >= $from && $age <= $to) return true; 
    } 
    return false; 
} 

$result_age = isAgeInRange($student_field['student_age'][0], $filters['age-pref'][0]); 
0
$student_age = 43; 
$age_pref = array(
    "31-35,36-40" 
); 

function inrange($age, $range) 
    { 
    $chunks = explode(",", $range[0]); 
    foreach($chunks as $chunk) 
     { 
     $val = explode("-", $chunk); 
     if ($age >= (int)$val[0] && $age <= (int)$val[1]) 
      { 
      return true; 
      } 
     } 
    } 

echo inrange($student_age, $age_pref);