Home > Backend Development > PHP Tutorial > 二维数组按指定的键值排序

二维数组按指定的键值排序

WBOY
Release: 2016-06-20 13:02:20
Original
1040 people have browsed it

将二维数组按指定的键值排序。

<p>/*</p>function:二维数组按指定的键值排序<br />author:www.scutephp.com<br />*/<br />function array_sort($array,$keys,$type='asc'){<br />	if(!isset($array) || !is_array($array) || empty($array)){<br />		return '';<br />	}<br />	if(!isset($keys) || trim($keys)==''){<br />		return '';<br />	}<br />	if(!isset($type) || $type=='' || !in_array(strtolower($type),array('asc','desc'))){<br />		return '';<br />	}<br />	$keysvalue=array();<br />	foreach($array as $key=>$val){<br />		$val[$keys] = str_replace('-','',$val[$keys]);<br />		$val[$keys] = str_replace(' ','',$val[$keys]);<br />		$val[$keys] = str_replace(':','',$val[$keys]);<br />		$keysvalue[] =$val[$keys];<br />	}<br />	asort($keysvalue); //key值排序<br />	reset($keysvalue); //指针重新指向数组第一个<br />	foreach($keysvalue as $key=>$vals) {<br />		$keysort[] = $key;<br />	}<br />	$keysvalue = array();<br />	$count=count($keysort);<br />	if(strtolower($type) != 'asc'){<br />		for($i=$count-1; $i>=0; $i--) {<br />			$keysvalue[] = $array[$keysort[$i]];<br />		}<br />	}else{<br />		for($i=0; $i<$count; $i++){<br />			$keysvalue[] = $array[$keysort[$i]];<br />		}<br />	}<br />	return $keysvalue;<br /><p>}</p>
Copy after login

例如有下列这样一个数组:

<p>$array=array(</p>	0=>array('id'=>8,'username'=>'scutephp'),<br />	1=>array('id'=>9,'username'=>'com'),<br />	2=>array('id'=>5,'username'=>'www')<br /><p>);</p>
Copy after login

现在需要将这个二维数组按id升序排列,则:

array_sort($array,'id','asc');
Copy after login


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