Home >Backend Development >PHP Tutorial >How to Sort a Multidimensional Array in PHP by an Inner Array\'s Field?

How to Sort a Multidimensional Array in PHP by an Inner Array\'s Field?

Linda Hamilton
Linda HamiltonOriginal
2024-11-29 06:14:101045browse

How to Sort a Multidimensional Array in PHP by an Inner Array's Field?

Sorting Multidimensional Arrays by Inner Array Field in PHP [duplicate]

Consider a multidimensional array representing a database-like structure, where each element denotes a row with inner arrays containing field name-value pairs. For instance:

Array
(
    [0] => Array
        (
            [name] => 'Sony TV'
            [price] => 600.00
        )

    [1] => Array
        (
            [name] => 'LG TV'
            [price] => 350.00
        )

    [2] => Array
        (
            [name] => 'Samsung TV'
            [price] => 425.00
        )  
}

The goal is to sort these rows based on the "price" field. The desired result is:

Array
(
    [0] => Array
        (
            [name] => 'LG TV'
            [price] => 350.00
        )

    [1] => Array
        (
            [name] => 'Samsung TV'
            [price] => 425.00
        )

    [2] => Array
        (
            [name] => 'Sony TV'
            [price] => 600.00
        )        
}

Solution:

To achieve this sorting, PHP offers the following simple solution:

array_multisort(array_column($yourArray, "price"), SORT_ASC, $yourArray);

Alternatively, the following snippet can be used to preserve outer array keys:

$col = array_column($yourArray, "price");
array_multisort($col, SORT_ASC, SORT_NUMERIC, $yourArray);

The above is the detailed content of How to Sort a Multidimensional Array in PHP by an Inner Array\'s Field?. 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