pea*_*ove 0 php loops sum twig
{% set totalPrice = 0 %}
{% for category, product in table %}
{% for key, value in product|last %}
{{ value }}
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
输出是:
60
2
Run Code Online (Sandbox Code Playgroud)
我现在尝试将这些值一起计算:
{% set totalPrice = 0 %}
{% for category, product in table %}
{% for key, value in product|last %}
{{ value }}
{% set totalPrice = value %}
{% endfor %}
{% endfor %}
Total: {{ totalPrice }}
Run Code Online (Sandbox Code Playgroud)
我期望的结果是:
60
2
Total: 62
Run Code Online (Sandbox Code Playgroud)
但我得到的结果是:
60
2
Total: 2
Run Code Online (Sandbox Code Playgroud)
您覆盖totalPrice
的值,而不是添加它。所以:使用set totalPrice = totalPrice + value
.
{% set totalPrice = 0 %}
{% for category, product in table %}
{% for key, value in product|last %}
{{ value }}
{% set totalPrice = totalPrice + value %}
{% endfor %}
{% endfor %}
Total: {{ totalPrice }}
Run Code Online (Sandbox Code Playgroud)