Home > Backend Development > PHP Tutorial > How to Sort Arrays and Data in PHP?

How to Sort Arrays and Data in PHP?

Linda Hamilton
Release: 2025-01-02 15:36:41
Original
951 people have browsed it

How to Sort Arrays and Data in PHP?

How can I sort arrays and data in PHP?

Basic One Dimensional Arrays

This includes multidimensional arrays, including arrays of objects, and sorting one array based on another.

Sorting Functions:

  • sort
  • rsort
  • asort
  • arsort
  • natsort
  • natcasesort
  • ksort
  • krsort

Multi Dimensional Arrays, Including Arrays of Objects

PHP requires a custom comparison function to sort complex values.

Steps:

  1. Create a comparison function that takes two elements and returns:

    • 0 if the elements are equal.
    • A value less than 0 if the first value is lower.
    • A value greater than 0 if the first value is higher.
  2. Use one of these functions:

    • usort
    • uasort
    • uksort

Custom Numeric Comparisons

If sorting by a numeric key:

function cmp(array $a, array $b) {
    return $a['baz'] - $b['baz'];
}
Copy after login

Objects

If sorting an array of objects:

function cmp($a, $b) {
    return $a->baz - $b->baz;
}
Copy after login

Sorting by Multiple Fields

For primary sorting by one field (e.g., "foo") and secondary sorting by another (e.g., "baz"):

function cmp(array $a, array $b) {
    if (($cmp = strcmp($a['foo'], $b['foo'])) !== 0) {
        return $cmp;
    } else {
        return $a['baz'] - $b['baz'];
    }
}
Copy after login

Sorting into a Manual Order

To sort into a specific order (e.g., "foo", "bar", "baz"):

function cmp(array $a, array $b) {
    static $order = array('foo', 'bar', 'baz');
    return array_search($a['foo'], $order) - array_search($b['foo'], $order);
}
Copy after login

Sorting One Array Based on Another

To sort one array based on another:

array_multisort($array1, $array2);
Copy after login

Array_column

As of PHP 5.5.0, you can use array_column to extract a specific column and sort the array accordingly:

array_multisort(array_column($array, 'foo'), SORT_DESC, $array);
Copy after login

The above is the detailed content of How to Sort Arrays and Data in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template