An PHP 2 d array sorting function share
- 2020-12-19 20:56:44
- OfStack
2 - dimensional array is often encountered in the development of PHP, but its sorting is not as convenient as 1 - dimensional array with built-in function, 2 - dimensional array sorting needs to write our own function to handle, here UncleToo to share 1 PHP2 - dimensional array sorting function:
Code:
Description of three parameters of the function:
$arr: Array to sort
$keys: Specifies which key value to sort by
$type: sort in ascending or descending order. Default is ascending
This PHP function allows you to sort a 2-dimensional array by the specified key value and return the sorted array.
Example call:
Code:
functionarray_sort($arr,$keys,$type='asc'){
$keysvalue= $new_array= array();
foreach($arras$k=>$v){
$keysvalue[$k] = $v[$keys];
}
if($type== 'asc'){
asort($keysvalue);
}else{
arsort($keysvalue);
}
reset($keysvalue);
foreach($keysvalueas$k=>$v){
$new_array[$k] = $arr[$k];
}
return$new_array;
}
Description of three parameters of the function:
$arr: Array to sort
$keys: Specifies which key value to sort by
$type: sort in ascending or descending order. Default is ascending
This PHP function allows you to sort a 2-dimensional array by the specified key value and return the sorted array.
Example call:
$newArray= array_sort($array,'price');