支持 Unicode 的 PHP 自然排序算法? [英] Natural sorting algorithm in PHP with support for Unicode?

查看:58
本文介绍了支持 Unicode 的 PHP 自然排序算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用自然顺序算法在 PHP 中使用 Unicode/UTF-8 字符对数组进行排序?例如(这个数组中的顺序是正确排序的):

Is it possible to sort an array with Unicode / UTF-8 characters in PHP using a natural order algorithm? For example (the order in this array is correctly ordered):

$array = array
(
    0 => 'Agile',
    1 => 'Ágile',
    2 => 'Àgile',
    3 => 'Âgile',
    4 => 'Ägile',
    5 => 'Ãgile',
    6 => 'Test',
);

如果我尝试使用 asort($array) 我会得到以下结果:

If I try with asort($array) I get the following result:

Array
(
    [0] => Agile
    [6] => Test
    [2] => Àgile
    [1] => Ágile
    [3] => Âgile
    [5] => Ãgile
    [4] => Ägile
)

并使用 natsort($array):

And using natsort($array):

Array
(
    [2] => Àgile
    [1] => Ágile
    [3] => Âgile
    [5] => Ãgile
    [4] => Ägile
    [0] => Agile
    [6] => Test
)

如何在 PHP 5 下实现返回正确结果顺序 (0, 1, 2, 3, 4, 5, 6) 的函数?所有多字节字符串函数(mbstring、iconv、...)都在我的系统上可用.

How can I implement a function that returns the correct result order (0, 1, 2, 3, 4, 5, 6) under PHP 5? All the multi byte string functions (mbstring, iconv, ...) are available on my system.

我想要 natsort() 值,而不是键 - 我明确定义键(并使用 asort() 而不是 sort())的唯一原因是为了简化工作找出unicode 值的排序哪里出错了.

I want to natsort() the values, not the keys - the only reason why I'm explicitly defining the keys (and using asort() instead of sort()) is to ease the job of finding out where the sorting of unicode values went wrong.

推荐答案

搞定了!

$array = array('Ägile', 'Ãgile', 'Test', 'カタカナ', 'かたかな', 'Ágile', 'Àgile', 'Âgile', 'Agile');

function Sortify($string)
{
    return preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1' . chr(255) . '$2', htmlentities($string, ENT_QUOTES, 'UTF-8'));
}

array_multisort(array_map('Sortify', $array), $array);

输出:

Array
(
    [0] => Agile
    [1] => Ágile
    [2] => Âgile
    [3] => Àgile
    [4] => Ãgile
    [5] => Ägile
    [6] => Test
    [7] => かたかな
    [8] => カタカナ
)

<小时>

更好:

if (extension_loaded('intl') === true)
{
    collator_asort(collator_create('root'), $array);
}

感谢@tchrist!

Thanks to @tchrist!

这篇关于支持 Unicode 的 PHP 自然排序算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆