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
Release: 2024-11-29 06:14:10
Original
944 people have browsed it

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
        )  
}
Copy after login

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
        )        
}
Copy after login

Solution:

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

array_multisort(array_column($yourArray, "price"), SORT_ASC, $yourArray);
Copy after login

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);
Copy after login

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!

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