将整数与多维数组进行比较

时间:2014-03-19 13:00:51

标签: php arrays multidimensional-array callback compare

我有以下数组和数字$num,我正在尝试检查$num是否等于或在每个元素的fromto范围内。如果条件为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;
        }

    }

3 个答案:

答案 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';