Two dimensional array ordering shared by php instances

  • 2021-06-28 11:26:17
  • OfStack

The PHP1 dimension array can be sorted using functions such as sort(), asort(), arsort().

The sort of the PHP2 dimension array needs to be customized.

The following functions sort a given 2-dimensional array by a specified key value, first looking at the function definition:


function array_sort($arr,$keys,$type='asc'){ 
 $keysvalue = $new_array = array();
 foreach ($arr as $k=>$v){
  $keysvalue[$k] = $v[$keys];
 }
 if($type == 'asc'){
  asort($keysvalue);
 }else{
  arsort($keysvalue);
 }
 reset($keysvalue);
 $index = 0;// Save Subscript Not Used $k, Subscript from 0 Start with $index;
 foreach ($keysvalue as $k=>$v){
  
  $new_array[$index] = $arr[$k];
  $index++;
 }
 return $new_array; 
} 

It can sort 2-D arrays by a specified key value, or it can specify an ascending or descending sort (ascending by default). Example usage:


$array = array(
 array('name'=>'Js','date'=>'2014-05-01'),
 array('name'=>'Sh','date'=>'2014-04-30'),
 array('name'=>'Bj','date'=>'2014-05-02')
);
$arrayList = array_sort($array,'date');
print_r($arrayList);


Related articles: