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:
Extract the values from the desired column into a separate array:
$price = array(); foreach ($inventory as $key => $row) { $price[$key] = $row['price']; }
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!