繁体   English   中英

将国家代码转换为国家名称

[英]Convert country code to country name

我想使用以下函数将一个国家的 ISO 代码转换为其名称:

function convertcodes($in, $type){
    $out = "";
    $long = array('Afghanistan' , 'Åland Islands' , 'Albania' , 'Algeria' , 'American Samoa' , 'Andorra');
    $short = array('af','ax','al','dz','as','ad');
    $in = trim($in);
    switch($type){
        case 'long':
            $out = str_replace($short, $long, $in);
        break;
        case 'short':
            $out = str_replace($long, $short, $in);
        break;
    }
return $out;
}

问题是它返回所有国家而不是我正在寻找的国家,因为它的字符串匹配。 我怎样才能让它与确切的字符串匹配? 使用 preg_replace 不适用于数组。

(显然实际的数组要长得多,为了不让我发布的代码太长,我在这里去掉了一部分。)

我会改用索引数组。

例如:

$array = [
    "af" => "Afghanistan",
    "ax" => "Åland Islands",
    // ... and so on
];

这样您就可以使用给定的短名称来检索长名称,反之亦然。

检索示例:

echo $array['af'] // returns Afghanistan
// or
echo array_search ("Afghanistan", $array) // returns af

您可以使用剪下的这段代码轻松地将现有的两个数组转换为一个数组(感谢@splash58 ):

$array = array_combine($short, $long);

Ionic的解决方案很好,可能是最好的,但如果您需要两个数组,请考虑以下一个

function convertcodes($in, $type){
    $result = false;
    $long = array('Afghanistan' , 'Åland Islands' , 'Albania' , 'Algeria' , 'American Samoa' , 'Andorra');
    $short = array('af','ax','al','dz','as','ad');
    $in = trim($in);
    switch($type){
        case 'long':
            $index = array_search($in, $long);
            if ($index !== false) {
                $result = $short[$index];
            }
        break;
        case 'short':
            $index = array_search($in, $short);
            if ($index !== false) {
                $result = $long[$index];
            }
        break;
    }
    return $result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM