0
$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");
0

1 Answer 1

1

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

Demo

See also: array_reduce() arsort()

Update

You will see some crazy results when you look at this code in different versions of PHP.

Sign up to request clarification or add additional context in comments.

8 Comments

Jack, Thanks "Parse error: syntax error, unexpected T_FUNCTION" $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), ); $grouped = array_reduce($inventory, function(&$result, $item) { @$result[$item['fruit']] += $item['price']; return $result; }, array());
@CanadaPHP Updated the answer to work with older versions of php.
@CanadaPHP What do you mean without you rewriting? Rewrite what exactly?
your updated code generated an error Warning: arsort() expects parameter 1 to be array, integer
@CanadaPHP I don't know what you mean, it runs fine here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.