我有以下数组和数字$num
,我正在尝试检查$num
是否等于或在每个元素的from
和to
范围内。如果条件为true,则返回该数组的对应或键,并停止进一步比较。我能够使用array_walk
实现此目的,但无法停止进一步的比较
Array
(
[_1395216158966_966] => Array
(
[from] => 1
[to] => 3
[rate] => 10
)
[_1395216219094_94] => Array
(
[from] => 3
[to] => 6
[rate] => 15
)
[_1395216219662_662] => Array
(
[from] => 6
[to] => 9
[rate] => 20
)
)
当前代码
array_walk($data, array($this, 'CalculateWeightCharge'), $weight)
public function CalculateWeightCharge($data, $needle, $num)
{
if($num >= $data['from'] && $num <= $data['to']){
return true;
}
}
答案 0 :(得分:2)
function compare($array, $num) {
foreach ($array as $key => $value) {
if ($num >= $value['from'] && $num <= $value['to']) // any condition here
return $key;
}
return null;
}
答案 1 :(得分:2)
function fn($numbers, $num)
{
foreach($numbers as $key=>$val)
{
if($num >= $val["from"] && $num <= $val["to"])
{
return $key;
}
}
return null;
}
答案 2 :(得分:0)
以下是检查$num
数组中每个范围内是否$array
的代码:
$result = array_filter($array, function ($v) use($num) {
return $num >= $v['from'] && $num <= $v['to'];
})
if (count($result) == count($array)) echo 'TRUE';