Home > Backend Development > PHP Tutorial > PHP example sharing two-dimensional array sorting_PHP tutorial

PHP example sharing two-dimensional array sorting_PHP tutorial

WBOY
Release: 2016-07-13 10:29:45
Original
1022 people have browsed it

PHP one-dimensional array can be sorted using functions such as sort(), asort(), arsort();

The sorting of PHP two-dimensional array needs to be customized.

The following function sorts a given two-dimensional array according to the specified key value. Let’s look at the function definition first:

Copy code The code is as follows:

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 the subscript unchanged with $k, use $index starting from 0;
foreach ($keysvalue as $k=>$v){


$new_array[$index] = $arr[$k];

$index++;
}
return $new_array;
}

It can sort the two-dimensional array according to the specified key value, and can also specify the ascending or descending sorting method (the default is ascending order). Usage example:

Copy code The code is as follows:

$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);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/770581.htmlTechArticlePHP one-dimensional array can be sorted using functions such as sort(), asort(), arsort(); PHP 2 The ordering of dimensional arrays needs to be customized. The following function is to perform a given two-dimensional array according to the specified key value...
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