【问题标题】:Twig loop and building hash树枝循环和构建哈希
【发布时间】:2023-03-28 10:58:01
【问题描述】:

我在使用 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 个小时,但我不知道我在哪里出错。 当我检查我的数组时,我会测试键“名称”是否存在

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

如果没有,我想用 key = 'name' 在哈希中添加一个新数组

有人有想法吗?谢谢你的阅读。

【问题讨论】:

  • 就个人而言,我只会为这种编码做一个树枝扩展。以 lineCategory = test | 结束生成线类别。生命太短暂了,不能把模板语言作为一种通用语言来工作。
  • 你应该是对的,但我从来没有自己做树枝扩展,所以我试着用我的知识来找到一个可行的解决方案,仅此而已。我

标签: symfony hash twig


【解决方案1】:

我认为您正在寻找类似于:

{% 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 %}

【讨论】:

  • 感谢您的提示,它的工作 =) 只是为每个人提供的一个小细节,我在“if”函数中添加了一个测试{% if listCategory[key] is defined %}
  • @Quovandius 不客气,我已经更新了答案以反映
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 2012-03-05
  • 2013-01-16
  • 2018-12-21
  • 1970-01-01
  • 2015-03-08
相关资源
最近更新 更多