Simple instance of php sorting arrays

  • 2020-12-09 00:46:45
  • OfStack


<?php  
class='pingjiaF' frameborder='0' src='https://www.ofstack.com' scrolling='no'>  
 Sort an array   
usort()  The function sorts an array using a user-defined function.   
*/  

function cmp($a, $b) // User-defined callback functions   
{  
if($a==$b) // If the two parameters are equal   
{  
return 0; // return 0  
}  
return($a>$b)?-1:1; // If the first 1 Is greater than the control 2 A return 1 , otherwise, -1  
}  
$a=array(3,2,5,6,1); // define 1 An array   
usort ($a,"cmp"); // Sort an array using a custom function   
foreach($a as $key=>$value) // Loop out sorted key-value pairs   
{  
echo "$key:$valuen";  
}  
/* 
 Note: If two elements compare identically, their order in the sorted array is undefined. to  php 4.0.6  Previously, user-defined functions would keep these elements in their original order. But since the  4.1.0  A new sorting algorithm is introduced, and the result will not be like this, because there is no sorting algorithm 1 An effective solution.  

*/  

// Sort array key names  uksort(array,sorttype)  
function cmp($a, $b) // User-defined callback functions   
{  
if($a==$b) // If the two parameters are equal   
{  
return 0; // return 0  
}  
return($a>$b)?-1:1; // If the first 1 Is greater than the control 2 A return 1 , otherwise, -1  
}  
$a=array(4=>"four",3 =>"three",20 =>"twenty",10=>"ten"); // define 1 An array   
uksort ($a,"cmp"); // Sorts array key names using a custom function   
foreach($a as $key=>$value) // Loop out sorted key-value pairs   
{ // www.ofstack.com  
echo "$key:$valuen";  
}/* 
uksort()  The function sorts an array by key name and maintains an index relationship using a user-defined comparison function.  

 Returns if successful  true Otherwise return  false .  

 If the array you want to sort needs to be used 1 Sort by an unusual standard, then you should use this function.  

 
 The custom function should take two arguments that will be included in the array 1 Fill in the key name. Compare the function in theta 1 Is less than, equal to, or greater than 2 Each parameter must be returned separately 1 An integer less than, equal to, or greater than zero.  

*/  

  
/* 
sort()  The function sorts the values of a given array in ascending order.  

 Note: This function assigns a new key name to a cell in an array. The original key name has been deleted.  

 Returns if successful  true Otherwise return  false .  

*/  

$fruits=array("lemon","orange","banana","apple"); // define 1 An array   
sort($fruits); // Sort the array   
foreach($fruits as $key=>$val) // Loop out the sorted key-value pairs of the array   
{  
echo "$key=$valn"; // Output key-value pairs   
}  


Related articles: