在使用 Symfony2 时,有什么方法可以在 Twig 模板中获取值数组的平均值吗? 我尝试了类似下面的代码,但它不起作用
{% set sumratings = 0 %}
{% set count = 0 %}
{% for rating in article.ratings %}
{% set sumratings = sumratings + rating.value %}
{% endfor %}
AVG: {{ sumratings / article.ratings.count }}
有什么想法吗?
最佳答案
我觉得应该这样
{% set sumratings = 0 %}
{% for rating in article.ratings %}
{% set sumratings = sumratings + rating.value %}
{% endfor %}
AVG: {{ sumratings / article.ratings|length }}
假设 rating.value
是一个整数
关于php - 使用 Twig 模板时,有没有办法从数组中获取平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10605253/