我有树枝语法和合并功能的问题...我有多个带有 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 %}
Run Code Online (Sandbox Code Playgroud)
我尝试了 3 个小时,但我不知道我在哪里犯了错误。当我检查数组时,我测试键“名称”是否存在
如果是,我想将元素的价格添加到哈希价格中
如果否,我想在哈希中添加一个新数组,其中 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 %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3741 次 |
| 最近记录: |