Thursday, 2 February 2017

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?


Answer



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);

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...