2015-11-13 63 views
0

我有一個問題,樹枝語法和合並功能...我有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小時,我不知道我做出了錯誤。 當我檢查我的數組,我測試,如果關鍵的「名稱」存在

如果是的,我想元的價格增加了哈希價格

如果沒有,我想添加一個新的陣列hash with key ='name'

任何人都有想法? thx爲您的閱讀。

+3

就個人而言,我只想讓對這種編碼的樹枝延伸。最後用lineCategory = test | generateLineCategory。生活太短,無法將模板語言作爲通用語言工作。 – Cerad

+0

你應該有權利,但我從來沒有使自己的樹枝延伸,所以我嘗試用我的知識來找到一個工作解決方案,就是這樣。 I – Quovandius

回答

3

我認爲你正在尋找類似的東西:

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

Thx爲你的提示,它的工作=)只是一個小細節爲每個人,我在'如果'函數添加測試 '{%如果listCategory [鍵]被定義%}' – Quovandius

+0

@Quovandius歡迎您,我已經更新了答案以反映 – Luke