php数组如何按拼音顺序排序

苏生不惑
  • 18.9k
php$pinyin = array(
        array('name'=>'梁朝伟','age'=>23),
        array('name'=>'andy','age'=>24),
        array('name'=>'黎明','age'=>19),
        array('name'=>'郭富城','age'=>20)
    );


name字段转为拼音然后按字母排序,如果第一个字母相同比较第二个,希望结果为

php$pinyin = array(
        array('name'=>'andy','age'=>24),
        array('name'=>'郭富城','age'=>20)
        array('name'=>'梁朝伟','age'=>23),
        array('name'=>'黎明','age'=>19),
    );

找到汉字转拼音库

回复
阅读 10.7k
6 个回答
sobright
  • 2k

最近也碰到了要对汉字排序的问题, Collator 效果还不错, 参考 Comparing UTF-8 String

$name = [...];
(new \Collator('zh-CN'))->asort($name);
var_dump( $name );

实际前后:

 0 => '袁次阳'
 1 => '段纪明'
 2 => '朱公伟'
 3 => '朱文渊'
 4 => '朱符'
 5 => '卢子干'
 6 => '皇甫义真'
 7 => '阎忠'
 8 => '王子师'
 9 => '士孙君荣'
 10 => '荀慈明'
 11 => '黄世英孙'
 12 => '赵子柔'
 13 => '蔡伯喈'
 14 => '蔡文姬'
 15 => '杨文先'
 16 => '杨德祖'
 17 => '吴匡'
 18 => '马翁叔'
 19 => '郑公业'
 20 => '丁建阳'
 21 => '尉韩暹'
 22 => '胡才'
 23 => '李乐'
 24 => '杨奉'
 25 => '张雅叔'
 26 => '杨丑'
 27 => '眭白兔'
 28 => '蒋石'
 29 => '吉本'
 30 => '吉文然'
 31 => '吉思然'
 32 => '耿季行'
 33 => '司直韦晃'
 34 => '郎中张钧'

=>

 13 => '蔡伯喈'
 14 => '蔡文姬'
 20 => '丁建阳'
 1 => '段纪明'
 32 => '耿季行'
 22 => '胡才'
 6 => '皇甫义真'
 11 => '黄世英孙'
 29 => '吉本'
 31 => '吉思然'
 30 => '吉文然'
 28 => '蒋石'
 34 => '郎中张钧'
 23 => '李乐'
 5 => '卢子干'
 18 => '马翁叔'
 9 => '士孙君荣'
 33 => '司直韦晃'
 27 => '眭白兔'
 8 => '王子师'
 21 => '尉韩暹'
 17 => '吴匡'
 10 => '荀慈明'
 7 => '阎忠'
 26 => '杨丑'
 16 => '杨德祖'
 24 => '杨奉'
 15 => '杨文先'
 0 => '袁次阳'
 25 => '张雅叔'
 12 => '赵子柔'
 19 => '郑公业'
 4 => '朱符'
 2 => '朱公伟'
 3 => '朱文渊'
$sort = array();
foreach($pinyin as $key => $item) {
    $py = zhcnToPinyin($item['name']);
    $pinyin[$key]['pinyin'] = $py;
    $sort[] = $py;
}

array_multisort($sort, SORT_ASC, $pinyin);

function zhcnToPinyin() {
   //TODO 汉字转拼音
}

楼上正解,手册看一下array_multisort()

不懂楼主的做法,汉字排序时本来就是按拼音顺序排的,因为汉字编码表本身就是按照字母顺序来的。echo "梁朝伟" < "黎明" 得到true
拼音排序还要用拼音库的都太缺乏基础知识了。

john_shine
  • 1
新手上路,请多包涵

@incNick 其实GBK编码也不是完全按照首字母排序的,你可以去查一查GBK编码表,希望大家不要被误导

宣传栏