PHP处理返回数据,指定按照数据中的字段排序

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

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;
  }

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

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

但愿能帮到你。atom

相关文章
相关标签/搜索