邮编以?开头的邮费是多少?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

从上面的例子中,如果一个用户想要获得一个交付,并且他们的邮政编码以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个字符上匹配用户的邮政编码。这可能说不通。要详细说明,请参见下文:

//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,因为我可以在之后转换逻辑。

如果您有看起来像有效的英国邮政编码的内容,则删除空格并只搜索数组,直到找到匹配:

$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;

一种选择是按邮政编码键的长度降序排列邮政编码/地区数组。这样,将首先检查较长的(更具体的)键。以上面的列表为例,它会变成这样…

$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;

最新更新