You are here

function views_aggregator_median in Views Aggregator Plus 8

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

Aggregates a field group as the median across its members.

This function was written for numbers, but also tries to do a half-decent job of dealing with the median of a group/column of strings.

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 calculate the median for.

Return value

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

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

File

./views_aggregator_functions.inc, line 475
views_aggregator_functions.inc

Code

function views_aggregator_median(array $groups, $field_handler) {
  $values = [];
  $column_cells = [];
  foreach ($groups as $group => $rows) {
    $group_cells = [];
    foreach ($rows as $num => $row) {
      $cell = views_aggregator_get_cell($field_handler, $num, FALSE);
      if ($cell !== FALSE && trim($cell) != '') {
        $group_cells[] = $cell;
        $column_cells[] = $cell;
      }
    }
    if (!empty($group_cells)) {
      sort($group_cells);
      $m = (int) (count($group_cells) / 2);
      $values[$group] = vap_num($group_cells[$m]) === FALSE || count($group_cells) % 2 ? $group_cells[$m] : ($group_cells[$m] + $group_cells[$m - 1]) / 2;
    }
  }
  if (!empty($column_cells)) {
    sort($column_cells);
    $m = (int) (count($column_cells) / 2);
    $values['column'] = vap_num($column_cells[$m]) === FALSE || count($column_cells) % 2 ? $column_cells[$m] : ($column_cells[$m] + $column_cells[$m - 1]) / 2;
  }
  return $values;
}