php - 使用 Twig 模板时,有没有办法从数组中获取平均值?

标签 php arrays symfony twig average

在使用 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/

相关文章:

PHP PDO 和 MySQL AGAINST() 函数

php - GitLab CI/CD-Nginx容器上的供应商目录

php - 无法在 php 中从 exec 或 shell_exec 执行 aws cli 命令

python - 在python中将2d数组读入3d数组

java - Android 上如何知道字符串是否在数组内?

php - 插入新游戏时出现 Symfony 错误 : Entities passed to the choice field must be managed. 也许将它们保留在实体管理器中?

php - Apache - htdocs 和/var/www/html

Javascript - 如果另一个值不存在,则从数组中删除值

forms - Controller Action 中的symfony2 : setting the value of a form field outside the form,

php - 如何在 symfony 4 和 Swiftmailer 中测试发送电子邮件