Php two-dimensional array sorting, php two-dimensional array sorting
// Create a $ arr two-dimensional array $ arr = array ('name' => 'E', 'age' => 5 ), array ('name' => 'B', 'age' => 2), array ('name' => 'A', 'age' => 1 ), array ('name' => 'C', 'age' => 3), array ('name' => 'D', 'age' => 4 ),);
Two functions: strnatcmp and strncmp
// Function echo strnatcmp ("ac", 'AB') that compares the two strings '). "<br/>"; // output 1 echo strncmp ("ac", 'AB', 1 ). "<br/>"; // output 0 because this function has a third parameter that limits only 1-bit comparison, that is, only
// Use usort to sort the values in the array using the User-Defined comparison function // sort the values in the array by key value name ($ arr, function ($, $ B) {return strnatcmp ($ a ['name'], $ B ['name']); // directly compare the name field of the Two-dimensional array for asc sorting }); dump ($ arr); // sort the length of the key value name usort ($ arr, function ($ a, $ B) {if (strlen ($ a ['name']) = strlen ($ B ['name']) return 0; return (strlen ($ a ['name'])> strlen ($ B ['name'])? 1:0 ;}); dump ($ arr );
Print function
function dump($data) { echo "<pre>"; print_r($data); echo "</pre>"; }
Sort sorts ArraysIt is applicable to one-dimensional index arrays without indexes.
Rsort sorts arrays in reverse orderConsistent with sort usage
Asort sorts ArraysAnd keep the index relationship to sort the values. It is generally applicable to one-dimensional arrays and maintains the index relationship.
Arsort sorts arrays in reverse order and maintains the index relationship.Consistent with asort usage
Ksort sorts arrays by key names
Krsort sorts arrays in reverse order by key name