Home > php教程 > php手册 > php实例分享之二维数组排序

php实例分享之二维数组排序

WBOY
Release: 2016-06-13 09:35:07
Original
933 people have browsed it

PHP一维数组的排序可以用sort(),asort(),arsort()等函数;

PHP二维数组的排序需要自定义。

以下函数是对一个给定的二维数组按照指定的键值进行排序,先看函数定义:

复制代码 代码如下:


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;//保存下标不变用$k,下标从0开始就用$index;
 foreach ($keysvalue as $k=>$v){

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

  $index++;
 }
 return $new_array;
}

它可以对二维数组按照指定的键值进行排序,也可以指定升序或降序排序法(默认为升序),用法示例:

复制代码 代码如下:


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

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template