You are here

function views_aggregator_average in Views Aggregator Plus 8

Same name and namespace in other branches
  1. 7 views_aggregator_functions.inc \views_aggregator_average()

Aggregates a field group as the average amongst its members.

Parameters

array $groups: An array of groups of rows, each group indexed by group value.

object $field_handler: The handler for the view column to find the minimum in.

int $precision_group: The number of decimals, if specified.

int $precision_column: The number of decimals, if specified.

Return value

array An array of values, one for each group and one for the column.

1 string reference to 'views_aggregator_average'
ViewsAggregatorResultsTest::testColumnResultFunctions in tests/src/Functional/Plugin/ViewsAggregatorResultsTest.php
Test the column functions.

File

./views_aggregator_functions.inc, line 197
views_aggregator_functions.inc

Code

function views_aggregator_average(array $groups, $field_handler, $precision_group, $precision_column) {
  $values = [];
  $sum_column = 0.0;
  $count_column = 0;
  foreach ($groups as $group => $rows) {
    $sum = 0.0;
    $count = 0;
    foreach ($rows as $num => $row) {

      // Do not count empty or non-numeric cells.
      $cell = vap_num(views_aggregator_get_cell($field_handler, $num, FALSE));
      if ($cell !== FALSE) {
        $sum += $cell;
        $count++;
      }
    }
    $average = $count == 0 ? 0.0 : $sum / $count;
    $values[$group] = empty($precision_group) ? $average : number_format($average, $precision_group, '.', '');
    $sum_column += $sum;
    $count_column += $count;
  }
  $average_column = $count_column == 0 ? 0.0 : $sum_column / $count_column;
  $values['column'] = empty($precision_column) ? $average_column : number_format($average_column, $precision_column, '.', '');
  return $values;
}