sAc*_*AcH 1 php symfony twig-extension
我想将键和值添加到树枝文件中的数组。但我面临以下问题"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 }}
Run Code Online (Sandbox Code Playgroud)
我只需要将键和值合并到数组中的语法。我尝试通过提供静态输入及其工作
{% set phoneNumbers = phoneNumbers|merge({ 'work':'(011)112-1233' }) %}
Run Code Online (Sandbox Code Playgroud)
但是它不适用于动态输入。请帮忙!!
您必须将密钥用大括号括起来:
{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}
Run Code Online (Sandbox Code Playgroud)
经过测试的工作示例:
{% set currPhone = {type: 'test'} %}
{% set phoneNumbers = {} %}
{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}
{% dump(phoneNumbers) %}
Run Code Online (Sandbox Code Playgroud)
我得到:
array:1 [?
"test" => "test"
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4472 次 |
| 最近记录: |