使用特殊字符排序

时间:2016-03-02 10:08:02

标签: php sorting special-characters

我有一个功能可以删除一系列值。

 function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
 }

效果很好,但它没有使用变音符号(ÁÉÍÓŮňďť等)对特殊字符进行排序。这些列在列表的末尾,即使它们属于更高级别(正确的排序就像AÁEÉnň等,但排序使它成为AEnÁÉň)。

有人知道如何实现这个目标吗?

1 个答案:

答案 0 :(得分:2)

I don't know if this works for you, but what I usually do is cast the string to ASCII, which will therefore sort your characters as if they were "regular" vocals.

function build_sorter($key) {
   return function ($a, $b) use ($key) {
       $stra = iconv('utf8', 'US-ASCII//TRANSLIT', $a[$key]);
       $strb = iconv('utf8', 'US-ASCII//TRANSLIT', $b[$key]);
       return strnatcmp($stra, $strb);
   };
}

Since we're transliterating to ASCII, you're getting the equivalent "A" for "Á" and therefore your sorter should now work properly.

  • Remember to set utf-8 to the encoding of your choice. I just assumed it to be UTF.
  • Your original strings are not affected.
  • Sorting may be returning inconsistent results with strings like "alter" and "älter"

[These are problems English speakers never have]