5

我需要为给定的国家名称加载 2 个字母的 ISO2 国家 ID。

现在,我使用以下方法来做到这一点:

// Method to Get countryId from CountryName
function getCountryId($countryName) {
    $countryId = '';
    $countryCollection = Mage::getModel('directory/country')->getCollection();
    foreach ($countryCollection as $country) {
        if ($countryName == $country->getName()) {
            $countryId = $country->getCountryId();
            break;
        }
    }
    $countryCollection = null;
    return $countryId;
}

用法:

var_dump(getCountryId('Germany'));

输出:

string(2) "DE"

是否有更简单/更快的方法来执行此操作,而不是每次都加载国家/地区集合并迭代它?

4

2 回答 2

2

令人惊讶的是,循环是实现这一目标的唯一方法。

国家名称存储在 XML 文件中lib/Zend/Locale/Data/,它们按语言环境(en、es、fr)和国家代码组织,而不是国家名称。

由于它不是 SQL 表,因此您不能添加WHERE子句(使用 Magento 的addFieldToFilter()),因此无论如何您都将遍历 XML 节点。

于 2013-09-13T16:04:59.923 回答
0

没有别的办法,因为翻译。这是获取国家名称的功能,您不能反转它

public function getName()
{
    if(!$this->getData('name')) {
        $this->setData(
            'name',
            Mage::app()->getLocale()->getCountryTranslation($this->getId())
        );
    }
    return $this->getData('name');
}
于 2013-09-13T13:10:07.003 回答