Home > Backend Development > PHP Tutorial > How to Sort an Associative Array by Column Value in PHP?

How to Sort an Associative Array by Column Value in PHP?

DDD
Release: 2024-12-26 16:43:09
Original
799 people have browsed it

How to Sort an Associative Array by Column Value in PHP?

How Can I Sort an Associative Array By Column Value?

This task requires employing the array_multisort() function, which can sort multidimensional arrays. To sort an array of associative arrays by a specific column value, such as "price," follow these steps:

  1. Extract the values from the desired column into a separate array:

    $price = array();
    foreach ($inventory as $key => $row)
    {
     $price[$key] = $row['price'];
    }
    Copy after login
  2. Call array_multisort() to sort the columns:

    array_multisort($price, SORT_DESC, $inventory);
    Copy after login

Alternatively, you can use array_column() in PHP 5.5.0 and later to extract the column values:

$price = array_column($inventory, 'price');

array_multisort($price, SORT_DESC, $inventory);
Copy after login

By following these steps, you can efficiently sort an array of associative arrays by the specified column value.

The above is the detailed content of How to Sort an Associative Array by Column Value in PHP?. 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