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
DDDOriginal
2024-12-26 16:43:09842browse

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'];
    }
  2. Call array_multisort() to sort the columns:

    array_multisort($price, SORT_DESC, $inventory);

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);

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!

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