将键和值合并到 Twig 文件中的数组中
Merge key and value into an array in Twig file
我想将键和值添加到 twig 文件中的数组中。但我面临以下问题 "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' }) %}
但它不适用于动态输入。请帮忙!!
您必须用大括号包裹您的密钥:
{% 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"
]
我想将键和值添加到 twig 文件中的数组中。但我面临以下问题 "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' }) %}
但它不适用于动态输入。请帮忙!!
您必须用大括号包裹您的密钥:
{% 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"
]