1

我想将键和值添加到树枝文件中的数组中。但我面临以下问题"Twig_Error_Syntax: A hash key must be a quoted string or a number"

{% set phoneCount = 0 %}
{% set phoneNumbers = {} %}
{% for currPhone in currBroker.phones %}
    {% if (currPhone.type == 'Work' or currPhone.type == 'Mobile') and phoneCount <= 2 and currPhone.number !='' %}
        {% set phoneCount = phoneCount + 1 %}                   
        {% set phoneNumbers = phoneNumbers|merge({ currPhone.type:currPhone.type }) %}
    {% endif %}
{% endfor %}
{{ phoneNumbers|print_r }}

我只需要将键和值合并到数组中的语法。我尝试通过提供静态输入及其作品

{% set phoneNumbers = phoneNumbers|merge({ 'work':'(011)112-1233' }) %}

但它不适用于动态输入。请帮忙!!

4

1 回答 1

6

你必须用大括号把你的钥匙包起来:

{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}

测试和工作示例:

{% set currPhone = {type: 'test'} %}
{% set phoneNumbers = {} %}
{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}
{% dump(phoneNumbers) %}

我得到:

array:1 [▼
  "test" => "test"
]
于 2015-06-30T12:12:31.377 回答