Home > Backend Development > PHP Tutorial > How Can I Sort an Associative Array by a Specific Column Value in PHP?

How Can I Sort an Associative Array by a Specific Column Value in PHP?

Patricia Arquette
Release: 2024-12-17 10:25:25
Original
245 people have browsed it

How Can I Sort an Associative Array by a Specific Column Value in PHP?

Sorting an Associative Array by Column Value

Given an array of associative arrays, the task is to sort the elements based on a specific column value. For instance, consider the following array:

$inventory = array(
  array("type" => "fruit", "price" => 3.50),
  array("type" => "milk", "price" => 2.90),
  array("type" => "pork", "price" => 5.43),
);
Copy after login

The goal is to sort $inventory by the "price" column, resulting in:

$inventory = array(
  array("type" => "pork", "price" => 5.43),
  array("type" => "fruit", "price" => 3.50),
  array("type" => "milk", "price" => 2.90),
);
Copy after login

Solution using array_multisort()

To achieve this, we can use the array_multisort() function. It allows sorting multiple arrays by multiple columns.

Here's an example:

$price = array();
foreach ($inventory as $key => $row) {
    $price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
Copy after login

Alternatively, using array_column() (available since PHP 5.5.0):

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

By sorting the $price array, we indirectly sort $inventory since they share the same keys.

The above is the detailed content of How Can I Sort an Associative Array by a Specific 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template