How to Sort an Array of Associative Arrays by Value of a Given Key in PHP
If you want to learn how to sort an array of associative arrays by value of a given key in PHP, then read our tutorial. Here, you can find handy solutions.
In this article, we will cover a common issue: how to sort an array of arrays by the value of a given key with PHP.
Below, you can find the handiest methods with their examples.
Use array_multisort()
Let’s see how to use the <kbd class="highlighted">array_multisort()</kbd> function:
php array_multisort()
<?php
$inventory = [
[ 'type' => 'pork', 'price' => 5.43 ],
['type' => 'milk', 'price' => 2.9 ],
['type' => 'fruit', 'price' => 3.5]
];
$price = [];
foreach ($inventory as $key => $row) {
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
var_dump($inventory);
?>In PHP 5.5 and above versions, <kbd class="highlighted">array_column() </kbd> can be used instead of foreach.
Here is how to do that:
php array_column()
<?php
$inventory = [
[ 'type' => 'pork', 'price' => 5.43 ],
['type' => 'milk', 'price' => 2.9 ],
['type' => 'fruit', 'price' => 3.5]
];
$price = array_column($inventory, 'price');
array_multisort($price, SORT_DESC, $inventory);
var_dump($inventory);
?>Use Custom Comparison Function
Another option is using the custom comparison function. It is a pretty quick and handy solution to the problem.
Here is the example:
php custom comparison
<?php
$inventory = [
[ 'type' => 'pork', 'price' => 5.43 ],
['type' => 'milk', 'price' => 2.9 ],
['type' => 'fruit', 'price' => 3.5]
];
function invenDescSort($item1, $item2)
{
if ($item1['price'] == $item2['price']) {
return 0;
}
return $item1['price'] < $item2['price'] ? 1 : -1;
}
usort($inventory, 'invenDescSort');
var_dump($inventory);
?>It will produce:
php custom comparison
array(3) {
[0] =>
array(2) {
'type' =>
string(4) "pork"
'price' =>
double(5.43)
}
[1] =>
array(2) {
'type' =>
string(5) "fruit"
'price' =>
double(3.5)
}
[2] =>
array(2) {
'type' =>
string(4) "milk"
'price' =>
double(2.9)
}
}In this tutorial, we represented two methods of sorting an array of arrays by the value of a given key with PHP.
However, there are other possible solutions to the issue. You can find more information and options on this page.