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?
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:
From Sort an array of associative arrays by value of given key in php:
uasort (http://php.net/uasort) allows you to sort an array by your own defined function. In your case, that's simple:
the simple solution :)
the output is,
Was tested on 100 000 records: Time in seconds(calculated by funciton microtime). Only for unique values on sorting key positions.
Solution of function of @Josh Davis: Spended time: 1.5768740177155
Mine solution: Spended time: 0.094044923782349
Solution: