Home >Backend Development >PHP Tutorial >How Can I Sort Multi-Dimensional Arrays in PHP by Value?

How Can I Sort Multi-Dimensional Arrays in PHP by Value?

DDD
DDDOriginal
2024-12-24 01:45:10217browse

How Can I Sort Multi-Dimensional Arrays in PHP by Value?

Sorting Multi-Dimensional Arrays by Value

Sorting data by a specific key value in a multi-dimensional array is a common task. This can be achieved through the use of a user-defined sorting function in conjunction with the usort() or uasort() function.

To sort an array by the "order" key, the following steps can be followed:

  1. Define a sorting function (PHP 5.2 or earlier):
function sortByOrder($a, $b) {
    if ($a['order'] > $b['order']) {
        return 1;
    } elseif ($a['order'] < $b['order']) {
        return -1;
    }
    return 0;
}
  1. Use usort() with custom sorter:
usort($myArray, 'sortByOrder');
  1. Anonymous function (PHP 5.3 ):
usort($myArray, function($a, $b) {
    if ($a['order'] > $b['order']) {
        return 1;
    } elseif ($a['order'] < $b['order']) {
        return -1;
    }
    return 0;
});
  1. Spaceship operator (PHP 7):
usort($myArray, function($a, $b) {
    return $a['order'] <=> $b['order'];
});
  1. Arrow function (PHP 7.4):
usort($myArray, fn($a, $b) => $a['order'] <=> $b['order']);

Multi-Dimensional Sorting:

To extend sorting to multiple dimensions, the sorting function can be used recursively:

usort($myArray, function($a, $b) {
    $retval = $a['order'] <=> $b['order'];
    if ($retval == 0) {
        $retval = $a['suborder'] <=> $b['suborder'];
        if ($retval == 0) {
            $retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
        }
    }
    return $retval;
});

Preserving Key Associations:

To maintain key associations during sorting, use uasort() instead of usort(). See the PHP manual for a comparison of array sorting functions.

The above is the detailed content of How Can I Sort Multi-Dimensional Arrays in PHP by Value?. 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