PHP中二维数组排序有关问题

WBOY
Release: 2016-06-13 12:23:59
Original
846 people have browsed it

PHP中二维数组排序问题

PHP中二维数组排序,可以使用PHP内置函数uasort()

【使用用户自定义的比较函数对数组中的值进行排序并保持索引关联】

回调函数如下:注意回调函数的返回值是负数或者是false的时候,表示回调函数的第一个参数在前,第二个参数在后排列

	$person = array(		array('num'=>'001','id'=>6,'name'=>'zhangsan','age'=>21),		array('num'=>'001','id'=>7,'name'=>'ahangsan','age'=>23),		array('num'=>'003','id'=>1,'name'=>'bhangsan','age'=>23),		array('num'=>'001','id'=>3,'name'=>'dhangsan','age'=>23),	);
Copy after login

	//负数或者false表示第一个参数应该在前	function sort_by_name($x,$y){		return strcasecmp($x['name'],$y['name']);	}
Copy after login
使用如下:

uasort($person,'sort_by_name');
Copy after login


下面给出一个二维数组排序的方法,供参考和面试使用:

	//$array 要排序的数组	//$row   排序依据列	//$type  排序类型[asc or desc]	//return 排好序的数组	function array_sort($array,$row,$type){		$array_temp = array();		foreach($array as $v){			$array_temp[$v[$row]] = $v;		}		if($type == 'asc'){			ksort($array_temp);		}elseif($type='desc'){			krsort($array_temp);		}else{					}		return $array_temp;	}
Copy after login

=====================================================================

这里顺便说一下PHP排序的几个函数

sort      对数组排序】一般适用于一维索引数组,不会保持索引

【rsort    对数组逆向排序】 和sort用法一致


【asort 对数组进行排序并保持索引关系】对值进行排序,一般适用于一维数组,保持索引关系

【arsort 对数组进行逆向排序并保持索引关系】和asort用法一致


【ksort 对数组按照键名排序

【krsort 对数组按照键名逆向排序

=====================================================================




版权声明:本文为博主原创文章,未经博主允许不得转载。

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!