A PHP two-dimensional array sorting function sharing

高洛峰
Release: 2023-03-03 21:38:01
Original
1160 people have browsed it

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; 
}
Copy after login

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');
Copy after login


For more PHP two-dimensional array sorting function sharing related articles, please pay attention to PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template