Home >Backend Development >PHP Tutorial >How to Sort a Multidimensional PHP Array by Sub-array Value?

How to Sort a Multidimensional PHP Array by Sub-array Value?

DDD
DDDOriginal
2024-12-06 00:54:10247browse

How to Sort a Multidimensional PHP Array by Sub-array Value?

Sorting a Multidimensional Array by Sub-array Value in PHP

In PHP, arrays can be multidimensional, meaning they can contain arrays within arrays. A common use case is to sort such arrays based on a specific key within the nested sub-arrays.

Sorting by a String Key

Consider the following array:

$array = [
    [
        'configuration_id' => 10,
        'id' => 1,
        'optionNumber' => '3',
        'optionActive' => 1,
        'lastUpdated' => '2010-03-17 15:44:12'
    ],
    [
        'configuration_id' => 9,
        'id' => 1,
        'optionNumber' => '2',
        'optionActive' => 1,
        'lastUpdated' => '2010-03-17 15:44:12'
    ],
    [
        'configuration_id' => 8,
        'id' => 1,
        'optionNumber' => '1',
        'optionActive' => 1,
        'lastUpdated' => '2010-03-17 15:44:12'
    ]
];

To sort this array in ascending order based on the 'optionNumber' key, we can use usort along with an anonymous function:

usort($array, function ($a, $b) {
    return strcmp($a['optionNumber'], $b['optionNumber']);
});

This function compares the 'optionNumber' values of each sub-array and returns 1 if the first value is greater, -1 if it's smaller, or 0 if they're equal. This comparison is case-sensitive.

Sorting by an Integer Key

If the 'optionNumber' key contains integers, we can use the following function:

usort($array, function ($a, $b) {
    return $a['optionNumber'] - $b['optionNumber'];
});

This comparison will sort the array in ascending numerical order.

Considerations

  • For PHP versions 5.3 and above, use the spaceship operator (<=>) instead of subtraction to prevent overflow/truncation problems.
  • Note that these solutions assume the 'optionNumber' key exists in all sub-arrays and is of the expected type.

The above is the detailed content of How to Sort a Multidimensional PHP Array by Sub-array 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