By field4000 on
Hi all,
Is it possible to get the SUM of a field within a view without using the Views Calc module?
The reason I do not want to use the Views Calc module is that it requires you to use Views Calc Table style - I need to use to use the unformatted style.
I have found this code below. Could it be tweaked to get the SUM of a field?
<?php
$view = views_get_current_view();
$view->execute();
$count = count( $view->result );
print "Showing <b>$count</b> results";
?>
Any help with the above would be much appreciated.
Cheers in advance.
Comments
Views 3
No.
Use Views 3. It has grouping support, giving you all the SUMs you need.
Use the latest -dev version, it's more stable than the alpha.
array_sum()
field4000,
I came to your post looking for the same answer, and though this was asked a while back, I thought I'd share my solution while it's still fresh since I got it working for me within the last hour or so. I too came across count() before figuring out a solution for this. No guarantees as to the efficiency, etc... of the code. I am assuming that it won't export as other views results would...? I have tested it with the date browser so that correct sums show for different months and everything seems to work correctly.
I use it in an offline app. and as a warning, I am a php/drupal noob...
What my parameters are:
What I did
1. So I first isolated via print_r() how I can access the custom field (php) data
And came to this in order to get the first result [0] to print:
2. Realised if I was to add everything up, I needed to go through each result, keep it and run it through the only sum function I know of, and that is array_sum()
An obvious thing to note is that the results passed to to array_sum() need to be numbers - I've found currency signs and thousand separators get in the way, so if that is the case I run any or all of the following before passing the numbers to array_sum():
Then I pass $lessdollar (or $lessthousand, whichever is last) through array_sum() and voila! Just print the result or if you need to, a handy code for adding back the delimiter after array_sum() and before printing is:
Happy to receive feedback from experts if I am going the completely wrong way about it or if there could be improvements made to my method... So far it has worked for me for things views calc cannot calculate... I also think performance might not be too fantastic for a large amount of data as you're having to go through the same results all over again... :)
Try something like this in
Try something like this in the footer (or wherever you want it - did some example calculations and manipulations):
--
Shawn