PHP实现获取第一个中文首字母并进行排序的方法

2019-05-01 15:15:58丽君

然后下一步,要对这个二维数据排序。我思考了很久,后来想到了方案,先在循环里调用这个取首字母的方法,然后以这个字母作为key,因为php里有根据key排序的方法,所以我的代码写成这样就搞定了:

//门店名称
$shopData = $this->_shopNamesArray;
//根据门店名称第一个汉字的首字母正序排序
$settles = $result['data'];
$settlesRes = array();
foreach ($settles as $sett) {
    $sname = $shopData[$sett['sid']];
    $sett['sname'] = $sname;
    $snameFirstChar = $this->_getFirstCharter($sname); //取出门店的第一个汉字的首字母
    $settlesRes[$snameFirstChar] = $sett;//以这个首字母作为key
}
ksort($settlesRes); //对数据进行ksort排序,以key的值升序排序

先把这些数据print出来看效果:

Array
(
  [B] => Array
    (
      [sid] => 2885842
      [recetcstoredpay] => 24000
      [recetclprinciple] => 23465
      [paytcstoredpay] => 5455
      [paytclprinciple] => 34900
      [sname] => 百宴餐饮---便宜坊烤鸭店
    )
  [D] => Array
    (
      [sid] => 5229673
      [recetcstoredpay] => 26000
      [recetclprinciple] => 45930
      [paytcstoredpay] => 24795
      [paytclprinciple] => 121800
      [sname] => 大众点评网
    )
  [H] => Array
    (
      [sid] => 16832117
      [recetcstoredpay] => 81600
      [recetclprinciple] => 470930
      [paytcstoredpay] => 506090
      [paytclprinciple] => 8000
      [sname] => 欢乐谷店
    )
  [J] => Array
    (
      [sid] => 3671092
      [recetcstoredpay] => 1280
      [recetclprinciple] => 46930
      [paytcstoredpay] => 128090
      [paytclprinciple] => 149800
      [sname] => 金凤区新馆
    )
  [Z] => Array
    (
      [sid] => 1858783
      [recetcstoredpay] => 2040
      [recetclprinciple] => 4465
      [paytcstoredpay] => 245
      [paytclprinciple] => 4900
      [sname] => 浙江西子宾馆
    )
)

完全正确,搞定了~

PS:这里再为大家推荐2款比较实用的相关在线排序工具供大家参考使用:

在线中英文根据首字母排序工具:
http://tools.jb51.net/aideddesign/zh_paixu

在线文本倒序翻转排序工具:
http://tools.jb51.net/aideddesign/flipped_txt

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php排序算法总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php常用函数与技巧总结》、《PHP错误与异常处理方法总结》、《php面向对象程序设计入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

相关文章 大家在看