duanchen7036 2011-10-28 13:18
浏览 60

如何在PHP中对UTF-8字符串数组进行排序?

need help with sorting words by utf-8. For example, we have 5 cities from Belgium.

$array = array('Borgloon','Thuin','Lennik','Éghezée','Aubel');
sort($array); // Expected: Aubel, Borgloon, Éghezée, Lennik, Thuin
              // Actual: Aubel, Borgloon, Lennik, Thuin, Éghezée

City Éghezée should be third. Is it possible to use/set some kind of utf-8 or create my own character order?

  • 写回答

6条回答 默认 最新

  • doushifang4382 2011-10-28 13:20
    关注

    This script should resolve in a custom way. I hope it help. Note the mb_strtolower function. You need to use it do make the function case insensitive. The reason why I didn't use the strtolower function is that it does not work well with special chars.

    <?php
    
    function customSort($a, $b) {
        static $charOrder = array('a', 'b', 'c', 'd', 'e', 'é',
                                  'f', 'g', 'h', 'i', 'j',
                                  'k', 'l', 'm', 'n', 'o',
                                  'p', 'q', 'r', 's', 't',
                                  'u', 'v', 'w', 'x', 'y', 'z');
    
        $a = mb_strtolower($a);
        $b = mb_strtolower($b);
    
        for($i=0;$i<mb_strlen($a) && $i<mb_strlen($b);$i++) {
            $chA = mb_substr($a, $i, 1);
            $chB = mb_substr($b, $i, 1);
            $valA = array_search($chA, $charOrder);
            $valB = array_search($chB, $charOrder);
            if($valA == $valB) continue;
            if($valA > $valB) return 1;
            return -1;
        }
    
        if(mb_strlen($a) == mb_strlen($b)) return 0;
        if(mb_strlen($a) > mb_strlen($b))  return -1;
        return 1;
    
    }
    $array = array('Borgloon','Thuin','Lennik','Éghezée','Aubel');
    usort($array, 'customSort');
    

    EDIT: Sorry. I made many mistakes in the last code. Now is tested.

    EDIT {2}: Everything with multibyte functions.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度