1

我需要根据 PHP 中的最小值和最大值在数组中查找匹配项。缺少精心设计的 foreach,if,elseif,then 子句,我怎样才能有效地获得匹配的行?

例如...给定数组$arr(如下)和数字4,我如何返回数组行123

$arr = array(
    0 => array( 'min' => 1,     'max' => 1,     'name' => 'alpha'),
    1 => array( 'min' => 1,     'max' => 9,     'name' => 'beta'),
    2 => array( 'min' => 1,     'max' => 19,    'name' => 'gamma'),
    3 => array( 'min' => 2,     'max' => 29,    'name' => 'delta'),
    4 => array( 'min' => 10,    'max' => 100,   'name' => 'epsilon'),
    5 => array( 'min' => 20,    'max' => 100,   'name' => 'zeta'),
    6 => array( 'min' => 30,    'max' => 100,   'name' => 'eta')
);

我希望把它变成一个函数。像这样的东西:

function findMatchingRows($n) {
    $arr = /*** see above ***/;
    /*** your answer! ***/
    return $matchingRows;
}

$n = 12;
print_r(findMatchingRows($n));

上面的预期结果应该是 rows 234。但我希望它适用于 1 到 100 之间的任何整数。

4

1 回答 1

3
$number = 4;
$result = array_filter($arr, function ($elem) use ($number) {
   return $elem['min'] <= $number && $number <= $elem['max'];
});
于 2013-01-23T05:00:32.360 回答