$inventory = array(
array("fruit"=>"orange", "price"=>3),
array("fruit"=>"kiwi", "price"=>2),
array("fruit"=>"apple", "price"=>3),
array("fruit"=>"apple", "price"=>3),
array("fruit"=>"apple", "price"=>3),
array("fruit"=>"orange", "price"=>3),
array("fruit"=>"banana", "price"=>10),
array("fruit"=>"banana", "price"=>10),
);
// what I wish to do is loop through this array and add all of the 'prices' for each // unique key 'fruit' and then sort them afterwards
// ex. the output I wish to achieve would be an array as such:
$sum_array = array("banana"=>"20", "apple"=>"9", "orange"=>"6", "kiwi"=>"2");
Well, just group them by fruit and then sort the end-result:
function groupFruits(&$result, $item)
{
$key = $item['fruit'];
@$result[$key] += $item['price'];
return $result;
}
$grouped = array_reduce($inventory, 'groupFruits', array());
arsort($grouped);
print_r($grouped);
See also: array_reduce()
arsort()
Update
You will see some crazy results when you look at this code in different versions of PHP.