代碼如下 |
複製代碼 |
function multi_array_sort($multi_array,$sort_key,$sort=sort_asc){ if(is_array($multi_array)){ foreach ($multi_array as $row_array){ if(is_array($row_array)){ $key_array[] = $row_array[$sort_key]; }else{ return -1; } } }else{ return -1; } array_multisort($key_array,$sort,$multi_array); return $multi_array; } |
array(
array('id'=>1,'data'=>'a'),
array('id'=>3,'data'=>'c'),
array('id'=>2,'data'=>'b')
);
php本身是有一個多維陣列排序的函數的。
代碼如下 |
複製代碼 |
bool array_multisort ( array $ar1 [, mixed $arg [, mixed $... [, array $... ]]] ) |
方法二
代碼如下 |
複製代碼 |
<?php //以時間inputdate為key值進行二維數組降序排列 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; } ?> |
方法三
代碼如下 |
複製代碼 |
<?php $a = array( 0=>array("id"=>1,"name"=>"小何","addr"=>"0:1"), 1=>array("id"=>2,"name"=>"小剛","addr"=>"0:1:2"), 2=>array("id"=>3,"name"=>"小軍","addr"=>"0:1:3"), 3=>array("id"=>4,"name"=>"公司","addr"=>"0:4"), ); function sort_by($array, $keyname = null, $sortby){ $myarray = $inarray = array(); foreach($array as $i=>$befree){ $myarray[$i] = $array[$i][$keyname]; } switch($sortby){ case 'asc': asort($myarray); break; case 'arsort': arsort($myarray); break; case 'natcasesor': natcasesor($myarray); break; } foreach($myarray as $key=>$befree){ $inarray[$key] = $array[$key]; } return $inarray; } print_r(sort_by($a,"addr","arsort")); print_r($a[2]["id"]); ?>
|