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

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

Linda Hamilton
Linda HamiltonOriginal
2025-01-01 01:05:17186browse

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

Sorting an Array of Associative Arrays by Column Value

Sorting data is a fundamental task in programming. When it comes to associative arrays, PHP provides several built-in functions to facilitate this process.

Consider the following array of associative arrays:

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

The task is to sort the elements of $inventory by the "price" column in descending order, resulting in:

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

Solution using array_multisort()

The array_multisort() function allows sorting an array (or multiple arrays) by multiple columns. To sort by "price" in descending order, the following code can be utilized:

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

Alternative Solution with array_column() (PHP 5.5.0 )

For PHP versions 5.5.0 and above, the array_column() function can be used to simplify the above code:

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

Usage

The sorted $inventory array can now be used as needed. For example, the following code would print the sorted array:

foreach ($inventory as $item) {
    echo $item['type'] . ": $" . $item['price'] . PHP_EOL;
}

Output:

pork: .43
fruit: .50
milk: .90

The above is the detailed content of How to Sort an Array of Associative Arrays by a 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