Home >Backend Development >PHP Tutorial >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), );
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), );
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);
Alternatively, using array_column() (available since PHP 5.5.0):
$price = array_column($inventory, 'price'); array_multisort($price, SORT_DESC, $inventory);
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!