key value being replaced by #39;key#39; when using merge() in twig(在树枝中使用 merge() 时,键值被“键替换)
问题描述
我正在尝试将键值对添加到数组中,并为所有不以_"开头的属性添加当前值.出于某种原因,合并将key"(即 slug)的值替换为字符串 'key'.
I am trying to add pairs of key value to an array with their current values for all those attributes not starting by '_'. For some reason, the merge replaces the value of "key" (i.e slug) with the string 'key'.
例如,当 slug 是唯一一个键不以'_'开头的属性时,
For example when slug is the only attribute with key not starting with '_',
key = slug
value = something
它的行为如下:
{% for key,value in app.request.attributes.all %}
{% if '_' != key | slice(0, 1) %}
{{ dump(key) }} // string(4) "slug"
{% set params = params | merge({ key : value}) %}
{{ dump(key) }} // string(4) "slug"
{% endif %}
{% endfor %}
{{ dump(params) }} // array(1) { ["key"]=> string(9) "something" }
我已经在它们旁边添加了转储返回的内容.
I have added what the dumps return next to them.
最终转储返回
array(1) { ["key"]=> string(9) "something" }
在我期待的时候
array(1) { ["slug"]=> string(9) "something" }
我会说这是一个与 Twig forgets array-keys 类似的问题,但结论关于那个问题,这是一个 mongodb 问题,我没有使用它.我正在处理请求中的属性.
I'd say it's a similar problem to Twig forgets array-keys but the conclusion on that question is that is a mongodb problem and I am not using it. I am working with attributes from the request.
由于某种原因,merge({ key : value}) 的行为类似于 merge({ 'key' : value}).
For some reason, the merge({ key : value}) is behaving as merge({ 'key' : value}).
推荐答案
您需要将变量用括号括起来才能将其用作键.
You need to wrap your variable with parenthesis to be able to use it as a key.
{% set params = params | merge({ (key) : value}) %}
这篇关于在树枝中使用 merge() 时,键值被“键"替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在树枝中使用 merge() 时,键值被“键"替换
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Laravel 仓库 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01