zoukankan      html  css  js  c++  java
  • THINKPHP_(1)_修改TP源码,支持对中文字符串按拼音进行排序。

    问题:TP从服务器数据中取出的collection数据,当进一步在网页中进行分页显示时,需要调用order函数,实现类似如下图的排序。

    当点击页面中的相关内容时,实现对服务器数据进行重排,就要调用TP编写的order函数。

    但是,上述属性中包括int属性,包括中文字符串属性,我们希望按单位名称和单位简称按汉字拼音进行排序,如何修改。

    解决方法

    将TP的order函数源码从(order函数位于think-helpersrcCollection.php文件中)

        public function order(string $field, string $order = 'asc')
        {
            return $this->sort(function ($a, $b) use ($field, $order) {
                
                    $fieldA = $a[$field] ?? null;
                    $fieldB = $b[$field] ?? null;
    
                    return 'desc' == strtolower($order) ? $fieldB > $fieldA : $fieldA > $fieldB;
                
            });
        }       

    改为:

        public function order(string $field, string $order = 'asc')
        {
            return $this->sort(function ($a, $b) use ($field, $order) {
                //添加对中文的支持。
                //xiaojie add代码,添加对中文的支持。
                $fieldA = $a[$field] ?? null;
                $fieldB = $b[$field] ?? null;
                //注意,如果取出的$fieldA是数字,就不能用preg_match。所以,应该加上一个字符串判断类型。因为有些时候会对数字进行排序。
    
                if (isset($fieldA) && isset($fieldB) && is_string($fieldA) &&is_string($fieldB) && preg_match("/[x7f-xff]/", $fieldA)){ //如果字段内容中有中文。
                    $coll = collator_create( 'zh-CN' );
                    $res  = collator_compare( $coll, $fieldA, $fieldB );
                    return 'desc' == strtolower($order) ? $res<0 : $res>0;
                }
                else{
    //                $fieldA = $a[$field] ?? null;
    //                $fieldB = $b[$field] ?? null;
    
                    return 'desc' == strtolower($order) ? $fieldB > $fieldA : $fieldA > $fieldB;
                }
            });
        }

    即可。

    你永远不知道未来会有什么,做好当下。技术改变世界,欢迎交流。
  • 相关阅读:
    ["Visual Studio快捷键" ,"Vs","IDEA快捷键"]
    文件夹
    x
    软考.第一章-信息化和信息系统
    软考.起航篇
    Global.asax.cs 为 /.aspx 执行子请求时出错。 Server.Transfer
    网关我选 Spring Cloud Gateway
    我面向 Google 编程,他面向薪资编程
    JDK 13 都已经发布了,Java 8 依然是最爱
    Spring Cloud 系列之 Spring Cloud Stream
  • 原文地址:https://www.cnblogs.com/xiaojieshisilang/p/14832880.html
Copyright © 2011-2022 走看看