【发布时间】: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 | 结束生成线类别。生命太短暂了,不能把模板语言作为一种通用语言来工作。
-
你应该是对的,但我从来没有自己做树枝扩展,所以我试着用我的知识来找到一个可行的解决方案,仅此而已。我