This article mainly introduces PHP implementation of two-dimensional array by the specified key name method, where the array record three person information in the Age field value of the order as an example, analysis of PHP two-dimensional array sorting operation skills, the need for friends can refer to the next
In this paper, we describe the way that PHP implements a two-dimensional array sorted by the specified key name. Share to everyone for your reference, as follows:
<?php/* a two-dimensional array sorted by the specified key value */function array_sort ($array, $keys, $type = ' asc ') {if (!isset ($array) | |!is_array ($array) | | Empty ($array)) {return '; }//Sort field names, such as: ID if (!isset ($keys) | | trim ($keys) = = ') {return '; }//Sort by, for example: DESC, ASC if (!isset ($type) | | $type = = "| |!in_array (strtolower ($type), Array (' ASC ', ' desc ')) {return '; }//define an array $keysvalue =array (); foreach ($array as $key + $val) {//Filters the sorted field values $val [$keys] = Str_replace ('-', ' ", $val [$keys]); $val [$keys] = Str_replace (",", $val [$keys]); $val [$keys] = Str_replace (': ', ', $val [$keys]); Puts the key name specified in the record into the array, such as: [0]=>5,[1]=>3,[2]=>6 $keysvalue [] = $val [$keys];//sort field, such as: id index = "sort Key Name} asort ($keysvalu e); Sorts in ascending order of values and preserves the index relationship between key names and key values, such as: [1]=>3,[0]=>5,[2]=>6 Reset ($keysvalue); The pointer re-points to the array first foreach ($keysvalue as $key + = $vals) {$keysort [] = $key;//0=>[1],1=>[0],2=>[2]} $keysvalue = Array (); $count =count ($keysort);//Sort record number if (Strtolower ($type)! = ' ASC ') {//descending for ($i = $count-1; $i>=0; $i-) {$keysvalue [] = $array [$keysort [$i]]; }}else{//Ascending for ($i =0; $i < $count; $i + +) {$keysvalue [] = $array [$keysort [$i]]; }} return $keysvalue;} $array =array (' name ' = ' Tom ', ' age ' = ' ' ', ' ' like ' = ' beer '), array (' name ' = ' Trump ', ' age ' = ' 50 ', ' Like ' and ' food '), array (' name ' = ' Jack ', ' age ' = ' ', ' like ' + ' travel '));p Rint_r (Array_sort ($array, ' Age ')); >
Operation Result:
Array ( [0] = = Array ( [name] + Tom [age] = [like ] = beer ) [1] = = Array ( [name] + Jack [age] = [like] + travel ) [2] = = Array ( [name ] = Trump [age] = [like] = food ))