当前位置: 首页 > 后端技术 > PHP

PHP数组多个字段分别排序

时间:2023-03-29 21:58:21 PHP

1.PHP数组数组按字段之一排序/***按字段和类型对数组排序,常用实用方法。*@paramarray$data*@paramstring$sort_filed*@paramstring$sort_typeSORT_ASCorSORT_DESC*/publicfunctionsortByOneField($data,$filed,$type){if(count($data)<=0){返回$data;}foreach($dataas$key=>$value){$temp[$key]=$value[$filed];}array_multisort($temp,$type,$data);return$data;}2.PHP数组Array按2个字段排序,先按第一个字段排序,再按第二个字段排序/***按字段和类型对数组排序,常用实用方法。*@paramarray$array*@paramstring$filed1*@paramstring$type1SORT_ASC或SORT_DESC*@paramstring$filed2*@paramstring$type2SORT_ASC或SORT_DESC*/publicfunctionsortByTwoFiled($data,$filed1,$type1,$filed2,$type2){如果(count($data)<=0){返回$data;}foreach($dataas$key=>$value){$temp_array1[$key]=$value[$filed1];$temp_array2[$key]=$value[$filed2];}array_multisort($temp_array1,$type1,$temp_array2,$type2,$data);return$users;}3.扩展方法sortMultiArray()最多支持对数组的3个字段进行排序,当然可以扩展,重载自定义方法实现对多维数进行排序。使用方法:sortArrayMultiFields($data,['score'=>SORT_DESC])sortArrayMultiFields($data,['score'=>SORT_DESC,'count'=>SORT_ASC])sortArrayMultiFields($data,['score'=>SORT_DESC,'count'=>SORT_ASC,'name'=>SORT_ASC])/***按字段和类型对多数组进行排序。*@paramdata$array*@paramcondition$array*/publicfunctionsortArrayMultiFields(&$data,$condition){if(count($data)<=0||empty($condition)){return$data;}$fieldsCount=count($condition);$fields=array_keys($condition);$types=array_values($condition);switch($fieldsCount){案例1:$data=$this->sort1Field($data,$fields[0],$types[0]);休息;情况2:$data=$this->sort2Fields($data,$fields[0],$types[0],$fields[1],$types[1]);休息;默认值:$data=$this->sort3Fields($data,$fileds[0],$types[0],$fileds[1],$types[1],$fileds[2],$types[2]);休息;}返回$data;}publicfunctionsort1Field(&$data,$filed,$type){if(count($data)<=0){return$data;}foreach($dataas$key=>$value){$temp[$key]=$value[$filed];}array_multisort($temp,$type,$data);返回$data;}publicfunctionsort2Fields(&$data,$filed1,$type1,$filed2,$type2){if(count($data)<=0){return$data;}foreach($dataas$key=>$value){$sort_filed1[$key]=$value[$filed1];$sort_filed2[$key]=$value[$filed2];}array_multisort($sort_filed1,$type1,$sort_filed2,$type2,$data);返回$data;}publicfunctionsort3Fields(&$data,$filed1,$type1,$filed2,$type2,$filed3,$type3){if(count($data)<=0){return$data;}foreach($dataas$key=>$value){$sort_filed1[$key]=$value[$filed1];$sort_filed2[$key]=$value[$filed2];$sort_filed3[$key]=$value[$filed3];}array_multisort($sort_filed1,$type1,$sort_filed2,$type2,$sort_filed3,$type3,$data);返回$数据;}