前言

本文主要给大家介绍了关于PHP获取汉字首字母并分组排序的相关内容,因经常我们在做项目的时候,会有按首字母排序的需求 比如: 美团的城市选择 http://www.meituan.com/index/changecity/initiative app中按字母搜索

利用PHP获取汉字首字母并且分组排序详解

正题

网上找了各种,不尽人意,于是,自己就写了一个,分享给大家。

<"htmlcode">
// 按首字母排序
$data = [
 ['id' => 1, 'area_name' => '山东'],
 ['id' => 2, 'area_name' => '江苏'],
 ['id' => 3, 'area_name' => '安徽'],
 ['id' => 4, 'area_name' => '福建'],
 ['id' => 5, 'area_name' => '江西'],
 ['id' => 6, 'area_name' => '广东'],
 ['id' => 7, 'area_name' => '广西'],
 ['id' => 8, 'area_name' => '海南'],
 ['id' => 9, 'area_name' => '河南'],
 ['id' => 10, 'area_name' => '湖南'],
 ['id' => 11, 'area_name' => '湖北'],
];
// 初始化,然后调用分组方法
$data = (new Character)->groupByInitials($data, 'area_name');

下面的结果是不是你想要的呢,不论是做app还是网页,都可以用

$data = array(
 'A' => array(
  0 => array(
   'id' => 3,
   'area_name' => '安徽',
   'initials' => 'A'
  )
 ) ,
 'F' => array(
  0 => array(
   'id' => 4,
   'area_name' => '福建',
   'initials' => 'F'
  )
 ) ,
 'G' => array(
  0 => array(
   'id' => 6,
   'area_name' => '广东',
   'initials' => 'G'
  ) ,
  1 => array(
   'id' => 7,
   'area_name' => '广西',
   'initials' => 'G'
  )
 ) ,
 'H' => array(
  0 => array(
   'id' => 8,
   'area_name' => '海南',
   'initials' => 'H'
  ) ,
  1 => array(
   'id' => 9,
   'area_name' => '河南',
   'initials' => 'H'
  ) ,
  2 => array(
   'id' => 10,
   'area_name' => '湖南',
   'initials' => 'H'
  ) ,
  3 => array(
   'id' => 11,
   'area_name' => '湖北',
   'initials' => 'H'
  )
 ) ,
 'J' => array(
  0 => array(
   'id' => 2,
   'area_name' => '江苏',
   'initials' => 'J'
  ) ,
  1 => array(
   'id' => 5,
   'area_name' => '江西',
   'initials' => 'J'
  )
 ) ,
 'S' => array(
  0 => array(
   'id' => 1,
   'area_name' => '山东',
   'initials' => 'S'
  )
 )
);

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com