multidimensional array array_sum
I have seen various posted about this question so am aware some answers to this may exist. however I am none the wiser after reading these.
I have an array that is like the following.
[0] => Array
(
[id] => 95659865986
[invoiceNumber] => 6374324
[invoiceTitle] => Monthly
[invoiceStatus] => Paid
[accountId] => 6235218753
[totalExVat] => 158.95
[dateCreated] => 1 Apr 2012
[vatAmount] => 20.00
)
All I wish to do is do array sum on the vatAmount
values of this array.
As the following doesnt seem to be doing much.
(array_sum($account_invoices['vatAmount'])
Solution 1:
If you have PHP 5.5+ you can do this without looping or using a callback (since function calls are relatively expensive) ... just use:
$sum = array_sum(array_column($account_invoices, 'vatAmount'));
Solution 2:
I would use array_map to reduce the array to only what is needed. Bear in mind, this will only work with PHP 5.3 onwards.
$total_vat = array_sum( array_map(
function($element){
return $element['vatAmount'];
},
$account_invoices));