我需要为给定的国家/地区名称加载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;
}
Run Code Online (Sandbox Code Playgroud)
用法:
var_dump(getCountryId('Germany'));
Run Code Online (Sandbox Code Playgroud)
输出:
string(2) "DE"
Run Code Online (Sandbox Code Playgroud)
有没有更容易/更快的方法来做这个而不是加载国家集合并每次迭代它?
令人惊讶的是,循环是实现这一目标的唯一方法。
国家/地区名称存储在 XML 文件中,lib/Zend/Locale/Data/并且按区域设置(en、es、fr)和国家/地区代码(而不是国家/地区名称)进行组织。
由于它不是 SQL 表,因此您无法添加子句WHERE(使用 Magento 的addFieldToFilter()),因此无论如何您都将循环遍历 XML 节点。