I have accented values as keys of an array in PHP. I want to sort by key, but it seems that the Collator object doesn't have this option, destroying the keys instead.
<?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)
}
CodePudding user response:
I've never used this class before, but I believe this is a simple matter of misunderstanding the PHP manual. 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. Then map the original data to the sorted array.
Code: (Demo)
$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);
Or (Demo)
$collator = new Collator('pt_BR');
$keys = array_keys($arr);
$collator->sort($keys);
var_export(
array_replace(
array_flip($keys),
$arr
)
);
Output:
array (
'África do Sul' => 1,
'Alemanha' => 1,
'China' => 5,
'EUA' => 13,
'Itália' => 2,
)