当查询数据时,要求最终返回数据按照某个字段排序,但是在SQL语句中或查询模型中无法直接按照此字段进行排序,则下面这个方法就很有效了。
先看代码:

public function res_sort($data,$sort_type,$field) {
       $sort = array(
           'direction' => $sort_type,
           'field'     => $field,
       );
       $arrSort = array();
       foreach($data AS $uniqid => $row){
           foreach($row AS $key=>$value){
               $arrSort[$key][$uniqid] = $value;
           }
       }
       if($sort['direction']){
           array_multisort($arrSort[$sort['field']], constant($sort['direction']), $data);
       }
       return $data;
  }

说明:data;sort_type是排序类型:SORT_ASC(升序),SORT_DESC(降序);$field是指定排序的字段。
使用:获取数据后,在需要使用的地方,调用此方法,传入参数,最终会返回排序好的数据。

//例
$new_data = $this->res_sort($data,'SORT_DESC','age');  //$new_data就是按照age降序排序后的数据

希望能帮到你。

posted on 2018-07-04 16:47  西瓜很甜哟  阅读(242)  评论(0编辑  收藏  举报