Home > php教程 > php手册 > 一个简单的PHP中多维数组的排序

一个简单的PHP中多维数组的排序

WBOY
Release: 2016-06-13 09:47:38
Original
1065 people have browsed it

要按多维数组中某个元素进行排序,在PHP中也是非常容易实现的,一个函数调用一个回调函数就搞定了,也可以php自带的函数

如array_multisort($a,$b),$a,$b是两个数组,如果排序之后,$a数组的第3个元素被排到了第一位,那么$b的第三个元素不管他在$b中的大小都会排在第一位。看看下边的程序运行结果:

 代码如下 复制代码

$a =array(100,80,50,10,0);
$b = array("c","f","q","e","z");
array_multisort($a,$b);
var_dump($a);
var_dump($b);
?>

运行结果:

 代码如下 复制代码

array(5) { [0]=> int(0) [1]=> int(10) [2]=> int(50) [3]=> int(80) [4]=> int(100) }
array(5) { [0]=> string(1) “z” [1]=> string(1) “e” [2]=> string(1) “q” [3]=> string(1) “f” [4]=> string(1) “c” }

自定义函数实现排序

 代码如下 复制代码

$arr = array(    
 
    'index'=>array( 'name'=>'首页','order'=>3),
 
    'intro'=>array( 'name'=>'企业概况','order'=>2),
 
    'news'=>array( 'name'=>'新闻动态','order'=>1 ),
 
    'product'=>array( 'name'=>'产品中心','order'=>4 ),
 
    'message'=>array( 'name'=>'访客留言','order'=>7 ),
 
    'position'=>array( 'name'=>'人才招聘','order'=>6),
 
    'contact'=>array( 'name'=>'联系我们','order'=> 5 )
 
);
 
uasort($arr, 'cmp');
 
public function cmp($a, $b){
 
   return $a['order'] - $b['order'];
 
}

这时$arr就是以order大小排序了,呵呵……

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