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!