[英]How can I sort an array by accented keys in PHP?
I have accented values as keys of an array in PHP.我在 PHP 中将重音值作为数组的键。 I want to sort by key, but it seems that the Collator object doesn't have this option, destroying the keys instead.我想按键排序,但似乎 Collator object 没有此选项,而是销毁密钥。
<?php
$arr = ['Brasil' => 3, 'África do Sul' => 5];
$collator = new Collator('pt_BR');
$collator->sort($arr);
var_dump($arr);
$arr = ['Brasil' => 3, 'África do Sul' => 5];
$collator->asort($arr);
var_dump($arr);
$arr = ['Brasil' => 3, 'África do Sul' => 5];
$collator->sortWithSortKeys($arr);
var_dump($arr);
?>
This will display:这将显示:
array(2) {
[0]=>int(3)
[1]=>int(5)
}
array(2) {
["Brasil"]=>int(3)
["África do Sul"]=>int(5)
}
array(2) {
[0]=>int(3)
[1]=>int(5)
}
How can I achieve my desired sorting below?如何在下面实现我想要的排序?
array(2) {
["África do Sul"]=>int(5)
["Brasil"]=>int(3)
}
I've never used this class before, but I believe this is a simple matter of misunderstanding the PHP manual .我以前从未使用过这个 class,但我相信这是一个简单的误解PHP 手册的问题。 To be perfectly honest, I was tricked by the method name as well.老实说,我也被方法名称欺骗了。 It doesn't sort by keys -- as you can see in the demo in the manual, the values are being sorted.它不按键排序——正如您在手册中的演示中看到的那样,值正在排序。
Because your keys are (by definition) unique, you can safely call array_keys()
to create a temporary indexed array where the original keys are now values.因为您的键(根据定义)是唯一的,所以您可以安全地调用array_keys()
来创建一个临时索引数组,其中原始键现在是值。 Then map the original data to the sorted array.然后 map 将原始数据放到排序后的数组中。
$arr = [
'Alemanha' => 1,
'China' => 5,
'EUA' => 13,
'Itália' => 2,
'África do Sul' => 1
];
$collator = new Collator('pt_BR');
$keys = array_keys($arr);
$collator->sort($keys);
foreach ($keys as $key) {
$result[$key] = $arr[$key];
}
var_export($result);
$collator = new Collator('pt_BR');
$keys = array_keys($arr);
$collator->sort($keys);
var_export(
array_replace(
array_flip($keys),
$arr
)
);
Output: Output:
array (
'África do Sul' => 1,
'Alemanha' => 1,
'China' => 5,
'EUA' => 13,
'Itália' => 2,
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.