Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array of associative arrays by value of a given key in PHP?

Given this array:

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

I would like to sort $inventory's elements by price to get:

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

How can I do this?

like image 972
Matt Avatar asked Oct 20 '09 22:10

Matt


People also ask

How do you sort an associative array by key?

The ksort() function sorts an associative array in ascending order, according to the key. Tip: Use the krsort() function to sort an associative array in descending order, according to the key. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.

What is used to sort associative array in descending order according to value?

The arsort() function sorts an associative array in descending order, according to the value.

How do I sort one array by another in PHP?

uksort() allows us to sort an array by keys using a user-defined comparison function that is called multiple times, every time with two keys (in our case, from the $user array);


2 Answers

You are right, the function you're looking for is array_multisort().

Here's an example taken straight from the manual and adapted to your case:

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

As of PHP 5.5.0 you can use array_column() instead of that foreach:

$price = array_column($inventory, 'price');  array_multisort($price, SORT_DESC, $inventory); 
like image 92
Josh Davis Avatar answered Oct 03 '22 23:10

Josh Davis


PHP 7+

As of PHP 7, this can be done concisely using usort with an anonymous function that uses the spaceship operator to compare elements.

You can do an ascending sort like this:

usort($inventory, function ($item1, $item2) {     return $item1['price'] <=> $item2['price']; }); 

Or a descending sort like this:

usort($inventory, function ($item1, $item2) {     return $item2['price'] <=> $item1['price']; }); 

To understand how this works, note that usort takes a user-provided comparison function that must behave as follows (from the docs):

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

And note also that <=>, the spaceship operator,

returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater

which is exactly what usort needs. In fact, almost the entire justification given for adding <=> to the language in https://wiki.php.net/rfc/combined-comparison-operator is that it

makes writing ordering callbacks for use with usort() easier


PHP 5.3+

PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use usort to sort our array, but it's a little more verbose and harder to understand:

usort($inventory, function ($item1, $item2) {     if ($item1['price'] == $item2['price']) return 0;     return $item1['price'] < $item2['price'] ? -1 : 1; }); 

Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like $item2['price'] - $item1['price'], we can't safely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass to usort has to return integers for usort to work properly:

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

This is an important trap to bear in mind when using usort in PHP 5.x! My original version of this answer made this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is precisely the reason that the easier-to-use spaceship operator was added to the language in PHP 7.

like image 42
Mark Amery Avatar answered Oct 03 '22 22:10

Mark Amery