Home > Backend Development > PHP Tutorial > How to Sort a Multidimensional PHP Array by a Nested Field Efficiently?

How to Sort a Multidimensional PHP Array by a Nested Field Efficiently?

DDD
Release: 2024-12-02 00:52:14
Original
863 people have browsed it

How to Sort a Multidimensional PHP Array by a Nested Field Efficiently?

How to Efficiently Sort a Multidimensional PHP Array by a Nested Field?

In PHP, it is possible to encounter multidimensional arrays representing tabular data, where each element holds an associative array of field-value pairs. The task of sorting this data by a specific field within the nested arrays can be achieved with ease.

Consider the following database-alike array:

$data = [
    [
        'name' => 'Sony TV',
        'price' => 600.00
    ],
    [
        'name' => 'LG TV',
        'price' => 350.00
    ],
    [
        'name' => 'Samsung TV',
        'price' => 425.00
    ]
];
Copy after login

To sort this array by the 'price' field, one can employ the array_multisort() function along with the array_column() function, which extracts a specific column (field) from the multidimensional array. The following snippet accomplishes this:

array_multisort(array_column($data, 'price'), SORT_ASC, $data);
Copy after login

This call will rearrange the array in ascending order based on the 'price' field while discarding the original outer array keys. The resulting sorted array will appear as:

[
    [
        'name' => 'LG TV',
        'price' => 350.00
    ],
    [
        'name' => 'Samsung TV',
        'price' => 425.00
    ],
    [
        'name' => 'Sony TV',
        'price' => 600.00
    ]
]
Copy after login

Alternatively, for PHP versions before 8, a two-liner solution was required due to reference passing restrictions:

$col = array_column($data, 'price');
array_multisort($col, SORT_ASC, $data);
Copy after login

The above is the detailed content of How to Sort a Multidimensional PHP Array by a Nested Field Efficiently?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template