在PHP中的自然排序算法与统一code支持? [英] Natural sorting algorithm in PHP with support for Unicode?

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

问题描述

是否有可能进行排序使用自然顺序算法PHP和统一code / 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($数组)我得到以下结果:

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($数组):

And using natsort($array):

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

我如何可以实现返回正确的结果顺序的功能(0,1,2,3,4,5,6)PHP 5下?所有的多字节字符串函数(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(),而不是排序())是缓解就业找出其中的 UNI code值排序的地方出了错。

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!

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

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