I know this was asked many times, but still I can't find bullet proof solution.
Here is my array which needs to be sorted alphabetically.
setlocale(LC_ALL, 'sl_SI.utf8');
$a = [
'č' => [...],
'a' => [...],
'š' => [...],
'u' => [...]
]
How can I sort it by keys?
Taken reference from this example:-Sort an array with special characters in PHP
Explanation:-
Get array keys using array_keys()
method
Sort keys based on iconv()
AND strcmp()
functions
Iterated over the sorted key array and get their corresponding value from initial array.Save this key value pair to your resultant array
Do like below:-
<?php
setlocale(LC_ALL, 'sl_SI.utf8');
$a = [
'č' => [12],
'a' => [23],
'š' => [45],
'u' => [56]
];
$index_array = array_keys($a);
function compareASCII($a, $b) {
$at = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
$bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
return strcmp($at, $bt);
}
uasort($index_array, 'compareASCII');
$final_array = [];
foreach($index_array as $index_arr){
$final_array[$index_arr] = $a[$index_arr];
}
print_r($final_array);
Output:- https://eval.in/990872
Reference:-
iconv()
strcmp()
uasort
Use strcoll()
.
setlocale(LC_ALL, 'sl_SI.utf8');
// setlocale(LC_ALL,"cs_CZ.UTF-8"); //for Czech characters etc.
uksort($a, 'strcoll');
You can use usort for sorting multidimensional arrays by value this way:
setlocale(LC_ALL, 'sl_SI.utf8');
// setlocale(LC_ALL,"cs_CZ.UTF-8"); //for Czech characters etc.
usort($posts, function($a, $b) {
return strcoll($a["post_title"], $b["post_title"]);
});
or for objects:
setlocale(LC_ALL, 'sl_SI.utf8');
// setlocale(LC_ALL,"cs_CZ.UTF-8"); //for Czech characters etc.
usort($posts, function($a, $b) {
return strcoll($a->post_title, $b->post_title);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With