如何在 PHP 数组排序中使用多个 sort_flags(使用 SORT_LOCALE_STRING 、 SORT_NATURAL)?
我想对 UTF8 语言使用 SORT_LOCALE_STRING + SORT_NATURAL 数字。
我想对以下数组进行排序:
$array=array('Alpha', 'Älpha1', 'Älpha2', 'Älpha10', 'Älpha3', 'Älpha4', 'Bravo');
排序后我最喜欢的结果:
Array
(
[0] => Alpha
[1] => Älpha1
[2] => Älpha2
[3] => Älpha3
[4] => Älpha4
[5] => Älpha10
[6] => Bravo
)
但是使用 SORT_LOCALE_STRING 时:
<?php
$array=array('Alpha', 'Älpha1', 'Älpha2', 'Älpha10', 'Älpha3', 'Älpha4', 'Bravo');
setlocale(LC_COLLATE, 'de_DE.UTF8', 'de.UTF8', 'de_DE.UTF-8', 'de.UTF-8');
sort($array, SORT_LOCALE_STRING);
print_r($array);
?>
结果:
Array
(
[0] => Alpha
[1] => Älpha1
[2] => Älpha10
[3] => Älpha2
[4] => Älpha3
[5] => Älpha4
[6] => Bravo
)
并且使用 SORT_NATURAL 时:
<?php
$array=array('Alpha', 'Älpha1', 'Älpha2', 'Älpha10', 'Älpha3', 'Älpha4', 'Bravo');
sort($array, SORT_NATURAL);
print_r($array);
?>
结果:
Array
(
[0] => Alpha
[1] => Bravo
[2] => Älpha1
[3] => Älpha2
[4] => Älpha3
[5] => Älpha4
[6] => Älpha10
)
我怎样才能得到这样的结果?!
Array
(
[0] => Alpha
[1] => Älpha1
[2] => Älpha2
[3] => Älpha3
[4] => Älpha4
[5] => Älpha10
[6] => Bravo
)
更新:
我终于找到了解决方案,通过使用 intl AND The Collator class .
首先,启用 PHP Extension intl。
然后:
<?php
$array=array('Alpha', 'Älpha1', 'Älpha2', 'Älpha10', 'Älpha3', 'Älpha4', 'Bravo');
$collator = new Collator('de_DE.UTF8');
$collator->setAttribute(Collator::NUMERIC_COLLATION, Collator::ON);
$collator->setAttribute(Collator::CASE_FIRST, Collator::LOWER_FIRST);
$collator->asort($array);
print_r($array);
?>
结果:
Array
(
[0] => Alpha
[1] => Älpha1
[2] => Älpha2
[4] => Älpha3
[5] => Älpha4
[3] => Älpha10
[6] => Bravo
)
最佳答案
问题是您要使用的两个标志几乎相互矛盾。 SORT_NATURAL 希望将值视为字符串和数字的混合,而 SORT_LOCALE_STRING 希望将其纯粹视为字符串。
不确定是否有更简单的方法,但此代码将所有字母转换为标准字母表(使用 iconv()
),对该数组进行排序(使用 asort
保留键和SORT_NATURAL
),然后替换回原始字符串(使用array_replace()
)...
$array=array('Alpha', 'Älpha1', 'Älpha2', 'Älpha10', 'Älpha3', 'Älpha4', 'Bravo');
setlocale(LC_ALL, "en_US.utf8");
$trans = $array;
array_walk($trans, function (&$data) {
$data = iconv("UTF-8", 'ASCII//TRANSLIT//IGNORE', $data);
});
asort($trans, SORT_NATURAL);
$array = array_replace($trans, $array);
print_r($array);
给...
Array
(
[0] => Alpha
[1] => Älpha1
[2] => Älpha2
[4] => Älpha3
[5] => Älpha4
[3] => Älpha10
[6] => Bravo
)
关于php - 如何在PHP数组排序中使用多个sort_flags(使用SORT_LOCALE_STRING,SORT_NATURAL)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58577558/