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

bojanz’s picture

I have found this code below. Could it be tweaked to get the SUM of a field?

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.

bokki’s picture

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:

  • using Views 2, Drupal 6
  • A Custom PHP field (see Views Custom field module) getting some number from the DB via $data (as far as I've read, Views_calc cannot touch Custom PHP field as it executes waaay before custom field comes into play: see #515832: No Integration with Views Custom Field)
  • 'Table' style view (I imagine this is irrelevant - only mentioning it for the purposes of identifiying the correct template to use - ie. one that gets all results, so for eg. not 'field.tpl')
  • For my 'table' case, adding the code below to the views-view-table.tpl.php (or an equivalent copy as per views theming instructions)

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:

<?php 
     print $view->style_plugin->rendered_fields[0]['phpcode']; 
?>

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

<?php 
//'for formalities sake' the following line was a recommendation on a forum (http://forums.devnetwork.net/viewtopic.php?f=1&t=109082&start=0&st=0&sk=t&sd=a) when I was searching how to get results into an array, though I've taken it out and put it back in with no change to what happens to the printed result.
     $array = array(); 

//foreach gets all the results from the array that I want to add up, and then puts it in $array[]. DO NOT FORGET THE SQUARE BRACKETS
     foreach ($view->style_plugin->rendered_fields as $getsubtotals) {
          $array[] = $getsubtotals['phpcode'];
     };

//add up the contents of the array
     $total = array_sum($array) . "\n";

//print the result
     print $total;
?>

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():

<?php 
     //for replacing a dollar sign with nothing
     $lessdollar = str_replace('$','',$array); 

      //for replacing a comma ',' thousand delimiter with nothing
     $lessthousand = str_replace(',','',$lessdollar);
?>

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:

<?php 
     //$total is result from array_sum(), 2 is the decimal places, '.' is decimal 'point', ',' is the thousand delimiter...
     $putbackformatting = number_format($total, 2, '.', ',');  
?>

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... :)

sdsheridan’s picture

Try something like this in the footer (or wherever you want it - did some example calculations and manipulations):

$view = views_get_current_view();
$view->execute();
$total_a = $total_b = 0;
foreach ( $view->result as $row ) {
  $total_a += $row->field_a;
  $total_b += $row->field_b;
}
if ( $total_a > 0 ) {
  print t('<b>Total a:</b> !ta<br><b>Total b:</b> !tb<br><b>Percent:</b> !pc%', array(
    '!ta' => number_format($total_a),
    '!tb' => number_format($total_b),
    '!pc' => number_format($total_b / $total_a * 100, 1),
  ));
}

--
Shawn