This article mainly introduces the method of PHP to implement two-dimensional array sorting according to the specified key name. Here, taking the array to record the age field value in the information of three people as an example, the operation of sorting the two-dimensional array in PHP is analyzed. For tips, friends who need them can refer to
. This article describes the method of sorting two-dimensional arrays by specified key names in PHP. Share it with everyone for your reference, the details are as follows:
<?php /*二维数组按指定的键值排序*/ function array_sort($array,$keys,$type='asc'){ if(!isset($array) || !is_array($array) || empty($array)){ return ''; } //排序字段名,如:id if(!isset($keys) || trim($keys)==''){ return ''; } //排序方式,如:desc、asc if(!isset($type) || $type=='' || !in_array(strtolower($type),array('asc','desc'))){ return ''; } //定义一个数组 $keysvalue=array(); foreach($array as $key=>$val){ //对排序字段值进行过滤 $val[$keys] = str_replace('-','',$val[$keys]); $val[$keys] = str_replace(' ','',$val[$keys]); $val[$keys] = str_replace(':','',$val[$keys]); //将记录中指定的键名放入数组中,如:[0]=>5,[1]=>3,[2]=>6 $keysvalue[] =$val[$keys];//排序字段,如:id 索引=》排序键名 } asort($keysvalue); //按值升序排序,且保持键名与键值之间的索引关系,如:[1]=>3,[0]=>5,[2]=>6 reset($keysvalue); //指针重新指向数组第一个 foreach($keysvalue as $key=>$vals) { $keysort[] = $key;//0=>[1],1=>[0],2=>[2] } $keysvalue = array(); $count=count($keysort);//排序记录数 if(strtolower($type) != 'asc'){//降序 for($i=$count-1; $i>=0; $i--) { $keysvalue[] = $array[$keysort[$i]]; } }else{//升序 for($i=0; $i<$count; $i++){ $keysvalue[] = $array[$keysort[$i]]; } } return $keysvalue; } $array=array( array('name'=>'Tom','age'=>'23','like'=>'beer'), array('name'=>'Trump','age'=>'50','like'=>'Food'), array('name'=>'Jack','age'=>'26','like'=>'Travel') ); print_r(array_sort($array,'age')); ?>
Running results:
Array ( [0] => Array ( [name] => Tom [age] => 23 [like] => beer ) [1] => Array ( [name] => Jack [age] => 26 [like] => Travel ) [2] => Array ( [name] => Trump [age] => 50 [like] => Food ) )
The above is the detailed content of Implementation method of sorting specified key names in php two-dimensional array. For more information, please follow other related articles on the PHP Chinese website!