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

How to Sort Arrays and Data in PHP?

Linda Hamilton
Linda HamiltonOriginal
2025-01-02 15:36:41952browse

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'];
}

Objects

If sorting an array of objects:

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

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'];
    }
}

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);
}

Sorting One Array Based on Another

To sort one array based on another:

array_multisort($array1, $array2);

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);

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!

Statement:
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