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'])
You could use the aggregate function SUM to get the sum of all the f_count directly in your query. You would combine this with $stmt->fetchColumn() to get the value of the first column (which would be the sum) of the first row (which will be the only row since we used an aggregate function).
PHP Multidimensional array is used to store an array in contrast to constant values. Associative array stores the data in the form of key and value pairs where the key can be an integer or string. Multidimensional associative array is often used to store data in group relation.
The array_sum() function returns the sum of all the values in an array(one dimensional and associative). It takes an array parameter and returns the sum of all the values in it. The only argument to the function is the array whose sum needs to be calculated.
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'));
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));
Just a way to do it:
$sum = 0;
foreach($account_invoices as $num => $values) {
$sum += $values[ 'vatAmount' ];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With