Home  >  Article  >  Backend Development  >  A PHP two-dimensional array sorting function sharing

A PHP two-dimensional array sorting function sharing

高洛峰
高洛峰Original
2016-12-22 11:27:371161browse

Two-dimensional arrays are often encountered in PHP development, but their sorting is not as convenient as using built-in functions for one-dimensional arrays. The sorting of two-dimensional arrays requires us to write our own functions. Here UncleToo shares a PHP with you Two-dimensional array sorting function:

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; 
}

The three parameters of the function are explained:

$arr: the array to be sorted

$keys: specify which key value to sort according to

$type: sorting method, ascending or descending order, default In ascending order

This PHP function can sort a two-dimensional array according to the specified key value and return the sorted array.

Call example:

$newArray= array_sort($array,'price');


For more PHP two-dimensional array sorting function sharing related articles, please pay attention to 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