根据首字母排序

最近在套前台页面,前端小姐姐的页面是这样的:

根据首字母排序
文章图片
界面1 需求很简单,就是根据title的首字母来排序,然后在根据首字母来分组展示。
当我看了我们的数据库里面的数据时,发现我们没有将title的首字母存进去,这就需要我们在代码中进行转换(将汉字转换为汉语拼音,在将汉语拼音转换为大写,截取出第一个字母来进行分组),这样说起来还是有点复杂昂,接下来就实现(我使用的是JFinal框架):

1、从数据库中查询出数据
public List queryOrgListPage(String orgTypeId, String title) { List params = new ArrayList(); String sql = "select * from station_config where status=1 and org_id=? "; params.add(orgTypeId); if (title != null || "".equals(title) || "null".equals(title)) { sql += (" and title like concat('%',?,'%') "); params.add(title); } try { return Db.find(sql, params.toArray()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }
【根据首字母排序】就是简单的将数据从数据库中查询出来供我们去处理
2、将title字段转换为汉语拼音,并且转换为大写,截取第一个字母,最后将这个字母存放到一个新增的字段中
// 将首字母先暂时存到一个闲置的字段中 for (int i = 0; i < orgLists.size(); i++) { Record record = orgLists.get(i); try { // 将title字段转换为汉语拼音,转换为大写,然后在截取第一个字母 record.set("initial", ConvertPinyin.getPinyin(record.get("title")).toUpperCase().substring(0, 1)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }

这里我们需要借助一个jar包,即pinyin4j-2.5.0.jar,没有的小伙伴可以去我这里下载:https://download.csdn.net/download/qq_32376365/10622225。
3、根据汉语拼音来排序
// list排序 Collections.sort(list, new Comparator() { public int compare(Record arg0, Record arg1) { String o1 = arg0.get("title"); String o2 = arg1.get("title"); for (int i = 0; i < o1.length() && i < o2.length(); i++) { int codePoint1 = o1.charAt(i); int codePoint2 = o2.charAt(i); if (Character.isSupplementaryCodePoint(codePoint1) || Character.isSupplementaryCodePoint(codePoint2)) { i++; } if (codePoint1 != codePoint2) { if (Character.isSupplementaryCodePoint(codePoint1) || Character.isSupplementaryCodePoint(codePoint2)) { return codePoint1 - codePoint2; }String pinyin1 = PinyinHelper.toHanyuPinyinStringArray((char) codePoint1) == null ? null : PinyinHelper.toHanyuPinyinStringArray((char) codePoint1)[0]; String pinyin2 = PinyinHelper.toHanyuPinyinStringArray((char) codePoint2) == null ? null : PinyinHelper.toHanyuPinyinStringArray((char) codePoint2)[0]; if (pinyin1 != null && pinyin2 != null) { // 两个字符都是汉字 if (!pinyin1.equals(pinyin2)) { return pinyin1.compareTo(pinyin2); } } else { return codePoint1 - codePoint2; } } } return o1.length() - o2.length(); } });



这段我也是在网上拔的,具体那个忘了,感谢老铁的代码 根据首字母排序
文章图片
缓解一下 这样我们就已经在后台处理好我们需要的数据了,但是现在的数据时每条数据都有一个initial字段,里面存放的是title的首字母,并没有进行分组,那么我们就要到页面上去分组展示了
4、去页面上进行分组展示
//获取组织机构列表 function getNewsList(newsTypeId,searchValue){ $.ajax({ url:"xxx", type:"post", data:xxx, dataType:"json", success:function(data){ if(data.code==200){ var orgList=data.data; $("input[name='searchvalue']").val(data.msg); var contentDiv=$("#organise_box"); contentDiv.empty(); if(orgList.length<=0){ contentDiv.hide(); return; }else{ contentDiv.show(); } var initialTemp="A"; //存放临时的大写首字母 var tag=1; //判断是否是第一次进入,用来控制首字母的显示 var flag = 12; for(var i=0; i

这样我们就在前台将数据分组展示。有不懂的可以私信我

    推荐阅读