我知道这个问题已经被问过很多次了,但是我还是找不到可靠的解决方案。
以下是需要按字母顺序排序的数组。
setlocale(LC_ALL, 'sl_SI.utf8');
$a = [
'č' => [...],
'a' => [...],
'š' => [...],
'u' => [...]
]
我该如何按键排序呢?
我知道这个问题已经被问过很多次了,但是我还是找不到可靠的解决方案。
以下是需要按字母顺序排序的数组。
setlocale(LC_ALL, 'sl_SI.utf8');
$a = [
'č' => [...],
'a' => [...],
'š' => [...],
'u' => [...]
]
array_keys()
方法获取数组键iconv()
和strcmp()
函数对键进行排序<?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);
参考:-
sort($index_array, SORT_LOCALE_STRING);
没有起作用:-https://eval.in/990875 - Alive to die - Anant使用strcoll()
函数。
setlocale(LC_ALL, 'sl_SI.utf8');
// setlocale(LC_ALL,"cs_CZ.UTF-8"); //for Czech characters etc.
uksort($a, 'strcoll');
您可以使用 usort 按值对多维数组进行排序:
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"]);
});
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);
});