问题描述
我需要为给定的国家/地区名称加载2个字母的ISO2国家/地区ID.
I need to load the 2 letter ISO2 country ID for a given country name.
现在,我使用以下方法执行此操作:
Right now, I use the following method to do this:
// 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"
是否有一种简便/快捷的方法来执行此操作,而不是每次都加载国家/地区集并对其进行遍历?
Is there a easier/quicker way to do this instead of loading the country collection and iterating through it every time?
推荐答案
令人惊讶的是,循环是实现此目标的唯一方法.
Surprisingly, looping is the only way you'll achieve this.
国家/地区名称存储在lib/Zend/Locale/Data/
中的XML文件中,并且按照地区(en,es,fr)和国家/地区代码(而不是国家/地区名称)进行组织.
The country names are stored in XML files in lib/Zend/Locale/Data/
and they're organized by locale (en, es, fr) and then country code, not country name.
由于它不是SQL表,因此无法添加WHERE
子句(使用Magento的addFieldToFilter()
),因此无论如何您都将遍历XML节点.
Since it's not a SQL table you can't add a WHERE
clause (using Magento's addFieldToFilter()
), so you'll be looping through the XML nodes anyway.
这篇关于Magento-从名称获取国家/地区ID-有没有更简单/更快捷的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!