1

我有一个 MySql 表,它存储来自州和城市列表的用户州和城市。我专门将每个州编码为两个字母的缩写版本(如华盛顿的 WA 和加利福尼亚的 CA),每个城市都有两个字母的缩写,城市名称的格式如下:科罗拉多州博尔德CO-boulder和犹他州盐湖城UT-salt-lake-city避免使用相同城市名称的不同州。UT-salt-lake-cityPHP在列下插入值( ) City,但是当我通过PHP调用变量时,它显示如下:Your location is: UT-salt-lake-city, Utah. 为了解决这个问题,我一直在制作这个变量列表

    if ($city == "AL-auburn") { $city = "Auburn"; }
    else if ($city == "AL-birmingham") { $city = "Birmingham"; }
    else if ($city == "GA-columbus") { $city = "Columbus"; $state = "Georgia"; }
    else if ($city == "AL-dothan") { $city = "Dothan"; }
    else if ($city == "AL-florence") { $city = "Forence"; }
    else if ($city == "AL-muscle-shoals") { $city = "Muscle Shoals"; }
    else if ($city == "AL-gadsden-anniston") { $city = "Gadsden Anniston"; }
    else if ($city == "AL-huntsville") { $city = "Huntsville"; }
    else if ($city == "AL-decatur") { $city = "Decatur"; }
    else if ($city == "AL-mobile") { $city = "Mobile"; }
    else if ($city == "AL-montgomery") { $city = "Montgomery"; }
    else if ($city == "AL-tuscaloosa") { $city = "Tuscaloosa"; }

有没有办法可以缩短这个过程,或者至少从一个单独的文件中调用它,这样我就不必每次想调用该位置时都复制/粘贴?

4

3 回答 3

3

怎么样的东西

$name = 'UL-salt-lake-city';
ucwords(str_replace("-"," ",substr($name, 3)));

转换为“盐湖城”

于 2012-10-10T03:18:39.833 回答
2

你在这里需要一个哈希图,你可以在 PHP 中将它作为一个数组来实现:

$cities = array(
    "AL-auburn"     => array("Auburn"),
    "AL-birmingham" => array("Birmingham"),
    "GA-columbus"   => array("Columbus", "Georgia"),
    ...
);

if (isset($cities[$city])) {
    list($city, $state) = $cities[$city] + array(null, null);
}

然后您还可以存储城市数组。


或者,您可以利用现有信息:

list($state, $city) = explode('-', $city, 2);

$city = ucwords(strtr($city, '-', ' '));

然后,您可以再次将带有 hashmap 的状态 2 字母代码映射到它们的长名称:

$states = array(
    'AL' => 'Alabama',
    'GA' => 'Georgia',
    ...
);

if (isset($states[$state])) {
    $state = $states[$state];
}
于 2012-10-10T03:38:55.217 回答
0

如果您需要的名称与其代码不直接对应,则可以使用关联数组:

$city_names = array(
    'CO-boulder' => 'Boulder, Colorado',
    'GA-columbus' => 'Columbus, Georgia',
    // ...
);
$name = $city_names[$city];
于 2012-10-10T03:29:13.617 回答