Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to get average values from an array when using a Twig template?

Is there any way of getting the average value of an array of value just inside a Twig template when using Symfony2? I tried something like the following code but it doesn't work

{% set sumratings = 0 %}
{% set count = 0 %}
{% for rating in article.ratings %}
  {% set sumratings = sumratings + rating.value %}
{% endfor %}
AVG: {{  sumratings / article.ratings.count  }}

Any idea?

like image 705
JeanValjean Avatar asked Oct 17 '25 19:10

JeanValjean


1 Answers

I think this should do it

{% set sumratings = 0 %}
{% for rating in article.ratings %}
  {% set sumratings = sumratings + rating.value %}
{% endfor %}
AVG: {{  sumratings / article.ratings|length }}

Assuming rating.value is an integer

like image 143
Peter Bailey Avatar answered Oct 19 '25 09:10

Peter Bailey