检查邮政编码是否在多个阵列中?

时间:2017-02-15 11:20:24

标签: php arrays

我有3个不同的区域,MyArea1,MyArea2,MyArea3。每个都有一系列邮政编码:

$myArea1=array("AB1","AC2","AD1");
$myArea2=array("BC1","BC2","BC3");
$myArea3=array("CD1","CD2","CD3");

我需要检查的邮政编码如下所示" BC2 4YZ"。

以下内容在检查完整匹配时不起作用:

if (in_array($row['postcode'], $myArea1)) { $Area = 'Area 1'; }
else if (in_array($row['postcode'], $myArea2)) { $Area = 'Area 2'; }    
else if (in_array($row['postcode'], $myArea3)) { $Area = 'Area 3'; }
else { $Area = 'No Match'; }

我有以下工作:

foreach ($myArea1 as $myArea1pc) {
    if (strpos($row['postcode'],$myArea1pc) !== false) {
        $Area = 'Area 1';                   
    }
}

但是有没有办法为我的所有数组循环呢?

编辑:有时可能会出现诸如" BC24"在我的阵列中。

1 个答案:

答案 0 :(得分:2)

我会尝试使用in_array

$input = $row['postcode'];

$areas = array(
    'Area 1' => array("AB1","AC2","AD1"),
    'Area 2' => array("BC1","BC2","BC3"),
    'Area 3' => array("CD1","CD2","CD3"),
);

// Take out the first 3 letter:
$part = substr(trim(str_replace(' ', '', $input)), 0, -3);

$Area = 'No match';
// Find which "area" array contains it
foreach ($areas as $k => $v) {
    if (in_array($part, $v)) {
        $Area = $k;
        break;
    }
}