如果邮政编码以??Javascript或PHP

如果邮政编码以??Javascript或PHP,javascript,php,Javascript,Php,我有一个英国的邮政编码列表,旁边有一个地区id。现在,交付产品的成本更高,这取决于用户居住的地区 例如,如果一个用户住在伯明翰,其邮政编码以B开头,他将获得免费送货,因为该邮政编码区域不收费 同样,如果用户的邮政编码以IM开头,他们必须支付更多的送货费用,因为该邮政编码区域更大 邮政编码列表示例: Postcode | Region AL | A BA | A BB | A BD | A B | B BH | B LN | D LS | D IV1 | E IV23 | F 从上面的例子中,如

我有一个英国的邮政编码列表,旁边有一个地区id。现在,交付产品的成本更高,这取决于用户居住的地区

例如,如果一个用户住在伯明翰,其邮政编码以B开头,他将获得免费送货,因为该邮政编码区域不收费

同样,如果用户的邮政编码以IM开头,他们必须支付更多的送货费用,因为该邮政编码区域更大

邮政编码列表示例:

Postcode | Region
AL | A
BA | A
BB | A
BD | A
B | B
BH | B
LN | D
LS | D
IV1 | E
IV23 | F
从上面的例子中,如果一个用户想要获得一个交付,并且他们的邮政编码以BA开头,那么我想应用地区a的交付费率

事实上,我有点困惑,我怎么能以编程的方式做到这一点。起初我以为我会做一些类似的事情:

$postcodes = [
    'AL'=>'A',
    'BA'=>'A',
    //And so on ....
];

//get the first 2 letters
$user_input = substr( $user_postcode, 0, 2 );

if(array_key_exists($user_input,$postcodes)){
    //Get the region code
    $region = $postcodes[$user_input];

    // Charge the user with the delivery rate specific to that user, then carry on 
}
但问题是,一些相似的邮政编码可能位于不同的地区,例如,IV1是E区,IV23是F区,如上图所示

这意味着我必须在1、2、3或4个字符上匹配用户的post代码。这可能没有道理。要详细说明,请参见以下内容:

//From Birmingham and is in region B
$user1_input = 'B';

//From Bradford and is in region A
$user1_input = 'BD';

//From Inverness and is in region E
$user1_input = 'IV1';
因此,如果用户输入来自伯明翰,并且用户输入以B开头,那么我如何区分一个也以B开头的邮政编码,但其中包含其他字母,从而使其成为不同的邮政编码呢

我正在尽力解释,希望这是有道理的。如果没有,请询问更多信息


谁能帮我解释一下我是如何做到这一点的?在Javascript或PHP中,因为我可以在以后转换逻辑。

一个选项是按邮政编码键的降序长度排列邮政编码/地区数组。这样,首先检查较长(更具体)的键。在上面的列表中,它会变成这样

$postcodes = array(
    "IV23" => "F",
    "IV1" => "E",
    "LS" => "D",
    "LN" => "D",
    "BH" => "B",
    "BD" => "A",
    "BB" => "A",
    "BA" => "A",
    "AL" => "A",
    "B" => "B",
);
完成后,只需在数组中循环,根据提供的邮政编码检查匹配项(从左侧开始),然后在找到匹配项时停止

foreach($postcodes as $code => $region)
{
    if($code == substr($user_postcode, 0, strlen($code)))
    {
        $shippingRegion = $region;
        break;
    }
}

echo $shippingRegion;

如果您的数组看起来像a,则删除空格并搜索数组,直到找到匹配项:

$lookup = [
   '' => 'X', // in case no match is found
   'AL'=>'A',
   'BA'=>'A',
    //And so on ....
];

function get_delivery_for($postcode)
{
   global $lookup;
   for ($x=5; $x>0 && !$result; $x--) {
      $result=$lookup[substr($postcode, 0, $x)];
   }
   return ($result);
}
请注意,上面的代码是为了说明,我建议使用更详细的代码,以避免抛出警告

$result=isset($lookup[substr($postcode, 0, $x)]) 
       ?  $lookup[substr($postcode, 0, $x)]
       : false;