确定值是否在数组范围内

时间:2014-11-15 07:02:09

标签: php arrays filter range

我有一个如下所示的数组:

[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
        )

我很难比较它们。有人可以帮助解决这里的逻辑吗?

谢谢!

2 个答案:

答案 0 :(得分: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]);

答案 1 :(得分: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);