Twig 循环和构建哈希

Twig loop and building hash

我对 Twig 语法和合并函数有疑问...我有多个对象,其中包含 2 个字段类别和价格。

我需要创建一个数组或散列(我想散列更简单,但......我都试过了)每个类别的价格总和。

所以我尝试了很多代码,最后一个是:

{% set test = [ {'category': 'description', 'price':  '1'}, { 'category': 'abc', 'price': '2'}, { 'category':'description', 'price': '3'} ] %}

{% set listCategory={} %}

{% for line in test %}

    {% set new_category = { 'category': line.category, 'price': line.price } %}

    {% if loop.first %}
        {% set listCategory = listCategory|merge([new_category]) %}
    {% else %}
        {% set flag = false %}

        {% for category in listCategory %}
            {% if line['category'] == new_category['category'] %}

                {% set tmp = line['price'] + new_category['price'] %}
                {# i try it too#}
                {% set category = category|merge([tmp]) %}

                {# or i try this#}
                {% set category = category|merge({ (category.price) : category.price + new_category.price }) %}

                {{ dump(listCategory) }}

            {% endif %}
        {% endfor %}
    {% endif %}

{% endfor %}

我尝试了 3 个小时,但我不知道哪里出错了。 当我检查我的数组时,我测试键 'name' 是否存在

如果是,我想将元素的价格添加到哈希价格中

如果不是,我想在散列中添加一个新数组,key = 'name'

有人有想法吗?感谢您的阅读。

我认为您正在寻找类似于以下内容的内容:

{% set test = [ {'category': 'description', 'price':  1}, { 'category': 'abc', 'price': 2}, { 'category':'description', 'price': 3} ] %}

{% set listCategory={} %}

{% for line in test %}

    {% set key = line.category %}

    {% if listCategory[key] is defined %}

        {# notice here that the key is in brackets () because otherwise it will be interpreted as the string "key" %}
        {% set listCategory = listCategory|merge({(key):listCategory[line.category]+line.price}) %}

    {% else %}

        {% set listCategory = listCategory|merge({(key):line.price}) %}

    {% endif %}

    {{ key }}: {{ listCategory[key] }}

{% endfor %}