PHP multidimensional array sort of usort uasort

  • 2020-03-31 20:50:59
  • OfStack

Numerically indexed array:
Bool usort(array &$array, callback $cmp_function)
The usort function sorts the specified array (argument 1) as specified (argument 2).
When we want to sort a multidimensional array, each element of the multidimensional array is an array type, and how do two arrays compare in size? This is user-defined (compare by the first element of each array or...) .

 
<?php 
//Define multidimensional array
$a = array( 
array("sky", "blue"), 
array("apple", "red"), 
array("tree", "green")); 
//Customize the array comparison function to compare by the second element of the array.
function my_compare($a, $b) { 
if ($a[1] < $b[1]) 
return -1; 
else if ($a[1] == $b[1]) 
return 0; 
else 
return 1; 
} 
//The sorting
usort($a, 'my_compare'); 
//The output
foreach($a as $elem) { 
echo "$elem[0] : $elem[1]<br />"; 
} 

?> 

The result is:
 
sky : blue 
tree : green 
apple : red 

Associative array:
Bool uasort(array &$array, callback $cmp_function)
Bool uksort(array &$array, callback $cmp_function)

Uasort, uksort is used in the same way as usort, where uasort() sorts the value of the associative array and uksort() sorts the key of the associative array.
 
<?php 
$a = array( 
'Sunday' => array(0,'7th'), 
'Friday' => array(5,'5th'), 
'Tuesday'=> array(2,'2nd')); 

function my_compare($a, $b) { 
if ($a[1] < $b[1]) 
return -1; 
else if ($a[1] == $b[1]) 
return 0; 
else 
return 1; 
} 
//Sort by the second element of the value of the $a array (7th,5th,2nd)
uasort($a, 'my_compare'); 
foreach($a as $key => $value) { 
echo "$key : $value[0] $value[1]<br />"; 
} 
//Sort by the second character (r,u,u) of the keyword in the $a array
uksort($a, 'my_compare'); 
foreach($a as $key => $value) { 
echo "$key : $value[0] $value[1]<br />"; 
} 

?> 

The result is:

Tuesday: 2 2 nd
Friday: 5 5 th
Sunday: 0 7 th
Friday: 5 5 th
Sunday: 0 7 th
Tuesday: 2 2 nd

Related articles: