2

I've setup a section for reviews with several fields as numbers for a rating 0-5, I'm trying to figure out how to get the total of all reviews and sum of all reviews to provide a single average for an entry the reviews relate to.

What's the best approach to this.

Example of my fields:

Value Condition Reception etc

all graded 0-5 (number fields).

So how to go through the foreach and get the sum of all fields from all reviews then divide by total reviews for the related entry to get the average for each field.

  • Are you looking to get the average for a single entry or an overall average across every entry in you reviews section? – Aaron Berkowitz Apr 11 '15 at 21:54
  • Hi Aaron, Douglas' code sample works, that will give me the average across each facet of a review, for the overall I will be able to define my own formula with weighting applied to each in order to calculate the total score out of 100 (as some facets have a lower importance to the overall score). – patrick C Apr 12 '15 at 10:30
  • 2
    Great! Be sure to mark his answer as correct! – Aaron Berkowitz Apr 12 '15 at 14:09
5

Something like this should work:

{% set reviews = craft.entries.section('reviews').relatedto(entry) %}
{% set value = 0 %}
{% set condition = 0 %}
{% set reception = 0 %}
{% set count = 0 %}
{% for review in reviews %}
    {% set value = value + review.value %}
    {% set condition = condition + review.condition %}
    {% set reception = reception + review.reception %}
    {% set count = loop.index %}
{% endfor %}
{% set averageValue = (value / count)|round(1, 'floor') %}
{% set averageCondition = (condition / count)|round(1, 'floor') %}
{% set averageReception = (reception / count)|round(1, 'floor') %}
| improve this answer | |
  • Hey Douglas, much appreciated, that works like a charm! – patrick C Apr 12 '15 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.