Locale based sorting of arrays in PHP gives different result on OS X than Ubuntu

纵饮孤独 提交于 2019-12-11 15:51:19

问题


Given the following array:

$foo = ["a", "B", "æ", "Æ", "c", "A", "b", "C", "1"];

Then I set the locale with setlocale(LC_ALL, ['nb_NO.UTF-8', 'no_NO.UTF-8']); and run the array through sort($foo, SORT_LOCALE_STRING).

In Ubuntu, the sorted array will then look like:

[
  0 => '1',
  1 => 'A',
  2 => 'a',
  3 => 'B',
  4 => 'b',
  5 => 'C',
  6 => 'c',
  7 => 'Æ',
  8 => 'æ',
]

While on Mac (OS X) I get:

[
  0 => '1',
  1 => 'A',
  2 => 'B',
  3 => 'C',
  4 => 'a',
  5 => 'b',
  6 => 'c',
  7 => 'Æ',
  8 => 'æ',
]

It seems OS X wants to sort strings starting with capital letters by themselves(ABC, then abc), while I would just like them to be together (AaBbCc).

Is there any way of having them sort the arrays the same way in PHP, or would I have to write a custom sorting method, using one of the u*sort() methods instead?

Edit: seems to be quite similar to the question this is marked as a duplicate of. Altough OS X still seems to sort upper- and lower case letters after each other instead of mixing them, it is fixable by adding strtolower() to the sorting function.


回答1:


The cleanest, most professional way to fix this issue would be to ensure that you are actually setting an identical locale in both environments. Please read though the manual and the comments presented below the specs for insights about how to properly set and get the locale. Setting the locale can be fiddly business, you may need to change the syntax for some, and declare fallback values for others. The toil is yours to undertake.

As for a hot/temporary fix, you can call usort() with the spaceship operator placed between an array of conditions. First, compare $a vs $b after multibyte-safe converting them both to uppercase, if that comparison is a tie, then the spaceship operator will make a comparison on the raw $a vs $b.

Code: (Demo)

$foo = ["a", "B", "æ", "Æ", "c", "A", "b", "C", "1"];

usort($foo, function($a, $b) {
    return [mb_strtoupper($a), $a] <=> [mb_strtoupper($b), $b];
});

var_export($foo);

Output:

array (
  0 => '1',
  1 => 'A',
  2 => 'a',
  3 => 'B',
  4 => 'b',
  5 => 'C',
  6 => 'c',
  7 => 'Æ',
  8 => 'æ',
)


来源:https://stackoverflow.com/questions/56036361/locale-based-sorting-of-arrays-in-php-gives-different-result-on-os-x-than-ubuntu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!