Home  >  Article  >  Backend Development  >  How to implement two-dimensional array sorting in PHP?

How to implement two-dimensional array sorting in PHP?

巴扎黑
巴扎黑Original
2016-11-21 14:49:551124browse

Two-dimensional arrays are often encountered in PHP development, but their sorting is not as convenient as one-dimensional arrays using built-in functions. (For one-dimensional array sorting, please refer to another article on this site [Detailed explanation of array sorting functions in PHP] Summary]). The sorting of two-dimensional arrays requires us to write our own functions. Here UncleToo will share with you a PHP two-dimensional array sorting function:

Code:

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

The three parameters of the function:

$arr: Array to be sorted

$keys: Specify which key value to sort according to

$type: Sorting method, ascending or descending order, the default is ascending order

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

Call example:

Php code

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


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