简体   繁体   English

如何使用带有重音字符的 PHP array_multisort

[英]How to use PHP array_multisort with accented characters

I currently have a multidimensional array I am sorting using array_multisort, however one of the columns has some special accented characters - for example Développé .我目前有一个多维数组,我正在使用 array_multisort 进行排序,但是其中一列有一些特殊的重音字符 - 例如Développé

Is there a way to sort these characters with their equivalent non accented letter é = e ?有没有办法用它们等效的非重音字母é = e对这些字符进行排序?

array_multisort($column1, SORT_ASC,SORT_STRING|SORT_FLAG_CASE, $column2, SORT_ASC,SORT_STRING|SORT_FLAG_CASE, $multid_array);

There are a few answers here on SO regarding this issue, but when I tried them in the past, it seemed that most of them were too dependant on the locale of the system or even str_replace with incomplete arrays .关于这个问题,这里有一些关于 SO 的答案,但是当我过去尝试它们时,似乎它们中的大多数过于依赖系统的区域设置,甚至str_replace 不完整 arrays So running the code would either create different results on different environment or would miss a couple of characters.因此,运行代码会在不同的环境中产生不同的结果,或者会遗漏几个字符。

In the end I found the best approach comes from this non-accepted answer .最后我发现最好的方法来自这个未被接受的答案 From my tests this approach works perfectly, independently from all local settings, and can be adapted for accents only è or different sets like æ根据我的测试,这种方法非常有效,独立于所有本地设置,并且可以仅适用于重音è或不同的设置,如æ

The base is the Transliterator class , part of the intl extension.基础是Transliterator class ,是国际扩展的一部分。 which is available from PHP 5.4 onwards.从 PHP 5.4 开始可用。 In most system it's either already bundled or can be installed with在大多数系统中,它要么已经捆绑在一起,要么可以与

pecl install intl`

More installation info here .更多安装信息在这里

Usage用法

How to use is quite straightforward使用方法非常简单

  1. Step 1: you initialise the Transliterator object第 1 步:您初始化音译器 object
$transliterator = Transliterator::createFromRules(':: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);

For a list of rules that can be applied to this function, please refer to this manual .有关可应用于此 function 的规则列表,请参阅 本手册 The ones used in the example already work for your specific use case.示例中使用的那些已经适用于您的特定用例。

  1. Step 2: you use it to transliterate your text第 2 步:您使用它来音译您的文本
$newstring = $transliterator->transliterate($string);

In your specific case, you need of course to apply to all the relevant elements of your array.在您的特定情况下,您当然需要应用于数组的所有相关元素。

You're not sharing the array structure, so I can not produce a clear example, but depending on the structure you can use foreach or array_walk or recursive functions to loop and change where needed.你没有共享数组结构,所以我无法给出一个清晰的例子,但是根据结构,你可以使用foreacharray_walk或递归函数在需要的地方循环和更改。 If you want to update your initial question with a sample from the array, we can be more precise.如果你想用数组中的样本更新你的初始问题,我们可以更精确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM