Home >Backend Development >PHP Tutorial >Introduction to PHP two-dimensional array sorting and default natural sorting methods

Introduction to PHP two-dimensional array sorting and default natural sorting methods

高洛峰
高洛峰Original
2016-12-22 11:36:361293browse

PHP two-dimensional array sorting function, default natural sorting, that is, sort sorting. Here you can specify multiple methods to sort by a certain value in the two-dimensional array. See the program comments below for details.

/** 
  * @function 二维数组自然排序 
  * @author www.phpernote.com 
  * @param array $array 需要排序的数组(二维) 
  * @param string key 需要根据哪个键排序 
  * @param string order 排序方式(SORT_ASC,SORT_DESC) 
  * @param string type 排序方法(SORT_REGULAR,SORT_NUMERIC,SORT_STRING) 
  * @return array sorted array. 
  */
 function phpSortArray($array,$key,$order="SORT_ASC",$type="SORT_REGULAR"){ 
     if(!is_array($array)||empty($$array)){ 
         return $array; 
     } 
     $ArgCount=func_num_args();//返回传递到目前定义函数的参数数目 
     for($I=1;$I<$ArgCount;$I++){ 
         $Arg=func_get_arg($I); 
         if(!eregi("SORT",$Arg)){ 
             $KeyNameList[]=$Arg; 
             $SortRule[]=&#39;$&#39;.$Arg; 
         }else{ 
             $SortRule[]=$Arg; 
         } 
     } 
     foreach($array AS $Key=>$Info){ 
         foreach($KeyNameList as $KeyName){ 
             ${$KeyName}[$Key]=$Info[$KeyName]; 
         } 
     } 
     $EvalString=&#39;array_multisort(&#39;.join(",",$SortRule).&#39;,$array);&#39;; 
     eval($EvalString); 
     return $array; 
 }


For more introduction to PHP two-dimensional array sorting and default natural sorting methods, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn