Home > Article > Backend Development > PHP two-dimensional array custom sorting
<?php //对二维数组自定义排序 function array_sort($arr,$keys,$type){ $keysvalue=array(); $i = 0; foreach($arr as $key=>$val) { $val[$keys] = str_replace("-","",$val[$keys]); $val[$keys] = str_replace(" ","",$val[$keys]); $val[$keys] = str_replace(":","",$val[$keys]); $keysvalue[] =$val[$keys]; } asort($keysvalue); //key值排序 reset($keysvalue); //指针重新指向数组第一个 foreach($keysvalue as $key=>$vals) { $keysort[] = $key; } $new_array = array(); if($type != "asc"){ for($ii=count($keysort)-1; $ii>=0; $ii--) { $new_array[] = $arr[$keysort[$ii]]; } }else{ for($ii=0; $ii<count($keysort); $ii++){ $new_array[] = $arr[$keysort[$ii]]; } } return $new_array; } $arr = array( array( 'name' => '学习', 'size' => '1235', 'type' => 'jpe', 'time' => '1921-11-13', 'class' => 'dd', ), array( 'name' => '中国功夫', 'size' => '153', 'type' => 'jpe', 'time' => '2005-11-13', 'class' => 'jj', ), array( 'name' => '编程', 'size' => '35', 'type' => 'gif', 'time' => '1997-11-13', 'class' => 'dd', ), array( 'name' => '中国功夫', 'size' => '65', 'type' => 'jpe', 'time' => '1925-02-13', 'class' => 'yy', ), ); echo '<pre class="brush:php;toolbar:false">'; print_r(array_sort($arr,'size','asc')); function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR") { if(!is_array($ArrayData)) { return $ArrayData; } // Get args number. $ArgCount = func_num_args(); // Get keys to sort by and put them to SortRule array. for($I = 1;$I < $ArgCount;$I ++) { $Arg = func_get_arg($I); if(!eregi("SORT",$Arg)) { $KeyNameList[] = $Arg; $SortRule[] = '$'.$Arg; } else { $SortRule[] = $Arg; } } foreach($ArrayData AS $Key => $Info) { foreach($KeyNameList AS $KeyName) { ${$KeyName}[$Key] = $Info[$KeyName]; } } $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);'; eval ($EvalString); return $ArrayData; } ?>