0

这是一个简单的函数,它将邮政编码作为输入,在正确的数组中找到邮政编码并返回相应的城市。

function zipcode_search($a){

$zip = (int)$a;
//arrays of zipcodes to corresponding cities
$FtMyers = array(33901,33902,33903,33905,33906,33907,33908,33911,33912,33913,33916,33917,33918,33919,33965,33966,33967,33990,33993,33994);
$Naples  = array(34101,34102,34103,34104,34105,34106,34107,34108,34109,34110,34112,34113,34114,34116,34117,34119,34120);
$Cape    = array(33904,33909,33910,33914,33915,33990,33991,33993);
$PtChar  = array(33948,33949,33952,33953,33954,33980,33981,33983);
$Bonita  = array(34133,34134,34135,34136);
$Marco   = array(34145,34146);
$Estero  = array(33928,33929);
$FMBeach = array(33931,33932);
$Sanibel = array(33957);

    if (in_array($zip, $Naples))
        {
            return "Naples, FL";
        }
elseif (in_array($zip, $Marco))
        {
            return "Marco Island, FL";
        }
elseif (in_array($zip, $Bonita))
        {
            return "Bonita Springs, FL";
        }
elseif (in_array($zip, $Estero))
        {
            return "Estero, FL";
        }
elseif (in_array($zip, $FtMyers))
        {
            return "Fort Myers, FL";
        }
elseif (in_array($zip, $FMBeach))
        {
            return "Ft. Myers Beach, FL";
        }
elseif (in_array($zip, $Cape))
        {
            return "Cape Coral, FL";
        }   
elseif (in_array($zip, $Sanibel))
        {
            return "Sanibel Island, FL";
        }
elseif (in_array($zip, $PtChar))
        {
            return "Port Charlotte, FL";
        }
else    {   return "Florida";}  
}

我知道我可以做得更好,同时提高它的功效。

4

3 回答 3

2
$pcodes = array(33901 => "Fort Myers, FL", 33902 => "Fort Myers, FL",
  33903 => "Fort Myers, FL", ...);

if (isset($pcodes[$zip]))
{
  return $pcodes[$zip];
}
else
{
  return 'Florida';
}
于 2012-06-10T03:02:14.640 回答
2
  • 邮政编码会随着时间而变化,因此您的功能不会是防弹的。如果需要,请使用像前锋这样的服务。
  • 您最好将这样的列表存储在数据库中。(除非您列出了您需要处理的每个邮政编码。它只是我所说的应该在数据库中的风口浪尖)

恕我直言,Ignacio Vazquez-Abrams 的解决方案很难维护——那里有很多复制和粘贴。这是一个替代方案,与您最初的类似:

function zipcode_search($zip){
    $city_zips = array(
        "Naples, FL" => array(34101,34102,34103,34104,34105,34106,34107,34108,34109,34110,34112,34113,34114,34116,34117,34119,34120),
        "Marco Island, FL" => array(34145,34146),
        // etc
    );

    foreach( $city_zips as $city => $zips ){
        if( in_array($zip, $zips) ){
            return $city;
        }
    }
}
于 2012-06-10T03:16:57.190 回答
1
function zipcode_search($zip){
    $zip_array['Fort Myers, FL'] = array(33901,33902,33903,33905,33906,33907,33908,33911,33912,33913,33916,33917,33918,33919,33965,33966,33967,33990,33993,33994);
    //... continue....

    foreach($zip_array as $city => $zips){
        if(in_array($zip, $zips)){
            return $city;
        }
    }
}  
于 2012-06-10T03:14:47.593 回答