我需要为给定的国家/地区名称加载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"
是否有更简单/更快捷的方式来执行此操作,而不是每次都加载国家/地区集合并进行迭代?
答案 0 :(得分:2)
令人惊讶的是,循环是实现这一目标的唯一方法。
国家/地区名称存储在lib/Zend/Locale/Data/
的XML文件中,它们按区域设置(en,es,fr)和国家/地区代码进行组织,而不是国家/地区名称。
由于它不是SQL表,因此无法添加WHERE
子句(使用Magento的addFieldToFilter()
),因此无论如何您都将循环遍历XML节点。
答案 1 :(得分:0)
由于翻译,没有别的办法。这是获取国家/地区名称的功能,您无法撤消
public function getName()
{
if(!$this->getData('name')) {
$this->setData(
'name',
Mage::app()->getLocale()->getCountryTranslation($this->getId())
);
}
return $this->getData('name');
}