题
我有一个包含西班牙语中语言名称的数组:
$lang["ko"] = "coreano"; //korean
$lang["ar"] = "árabe"; //arabic
$lang["es"] = "español"; //spanish
$lang["fr"] = "francés"; //french
.
我需要订购数组并保持索引关联,所以我使用 asort()带 sort_locale_string
.
setlocale(LC_ALL,'es_ES.UTF-8'); //this is at the beginning (config file)
asort($lang,SORT_LOCALE_STRING);
print_r($lang);
预期输出将按此顺序:
- 阵列([ar]=>árabe[ko]=> coreano [ES]=>Español[Fr]=>Francés)
但是,这就是我收到的:
- 阵列([ko]=> coreano [es]=>español[fr]=>francés[ar]=>árabe)
我错过了什么?感谢您的反馈意见!(我的服务器使用php 5.2.13版)
- 阵列([ko]=> coreano [es]=>español[fr]=>francés[ar]=>árabe)
解决方案
Try sorting by translitterated names:
function compareASCII($a, $b) {
$at = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
$bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
return strcmp($at, $bt);
}
uasort($lang, 'compareASCII');
print_r($lang);
其他提示
You defined your locale incorrectly in setlocale()
.
Change:
setlocale(LC_ALL,'es_ES.UTF-8');
To:
setlocale(LC_ALL,'es_ES');
Output:
Array ( [ar] => árabe [ko] => coreano [es] => español [fr] => francés )
The documentation for setlocale
mentions that
Different systems have different naming schemes for locales.
It's possible that your system does not recognize the locale as es_ES
. If you are on Windows, try esp_ESP
instead.
Try this
setlocale(LC_COLLATE, 'nl_BE.utf8');
$array = array('coreano','árabe','español','francés');
usort($array, 'strcoll');
print_r($array);
不隶属于 StackOverflow