PHP array sorting

Source: Internet
Author: User
Tags sorts

Sort () Sorts the indexed array in ascending order, whose inverse function is Rsort ()

Asort () Sorts the values of the associative array in ascending order, whose inverse function is Arsort ()

Ksort () Sorts the key names of the associative array in ascending order, whose inverse function is Krsort ()

Usort () Sorts multidimensional arrays (with Uasort () and Uksort () functions, as in the usage)

Definition and usage

The Usort () function uses a user-defined function to sort the array.

Note: If two elements compare the same result, their order in the sorted array is undefined. Before PHP 4.0.6, the user-defined function retains the original order of these elements. However, because of the introduction of a new sorting algorithm in 4.1.0, the result will not be this, because there is no effective solution to this.

Note: This function assigns the new key name to the element in the array . This will delete the original key name.

Grammar
Usort (Array,sorttype)
Parameters Description
Array Necessary. Specifies the array to sort.
function

Necessary. User-defined functions.

The function must be designed to return 1, 0, or 1, and should accept two parameters for comparison and work in a manner similar to the following:

  • If a = B, returns 0
  • If a > B, return 1
  • If a < B, return-1
Example
<?phpfunction my_sort ($a, $b)  {  if ($a = = $b) return 0;  return ($a > $b)? -1:1;  } $arr = Array ("Peter", "Glenn", "Cleveland", "Peter", "Cleveland", "Glenn"), Usort ($arr, "My_sort");p Rint_r ($arr); >

Output:

Array ([0] = peter[1] = glenn[2] = cleveland[3] = peter[4] = glenn[5] = Cleveland)

Example 2

function compare ($a, $b) {
if ($a [1]== $b [1]) {
return 0;
}elseif ($a [1]> $b [1]) {
return 1;
}else{
return-1;
}
}

$arr =array (
Array ("DF", 123),
Array ("AA", 333),
Array ("GG", 222)
);
Print_r ($arr);

echo "<br>";
Usort ($arr, ' compare ');

Print_r ($arr);

PHP array sorting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.