【问题标题】:How can I sum values with twig in loop?如何在循环中用树枝对值求和?
【发布时间】:2019-11-22 16:15:59
【问题描述】:
  {% set totalPrice = 0 %}
  {% for category, product in table %}
    {% for key, value in product|last %}
         {{ value }}
    {% endfor %}
  {% endfor %}

输出是:

60
2

我现在尝试将这些值一起计算:

   {% set totalPrice = 0 %}
      {% for category, product in table %}
        {% for key, value in product|last %}
             {{ value }}
             {% set totalPrice = value %}
        {% endfor %}
      {% endfor %}
      Total:    {{ totalPrice }}

我期望的结果是:

60
2
Total: 62

但我得到的结果是:

60
2
Total: 2

【问题讨论】:

    标签: php loops sum twig


    【解决方案1】:

    您覆盖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 }}
    

    【讨论】:

      猜你喜欢
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多