在树枝中使用 merge() 时,键值被“键"替换

2022-01-22 00:00:00 merge key php symfony twig

我正在尝试将键值对添加到数组中,并为所有不以_"开头的属性添加当前值.出于某种原因,合并将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}) %}

相关文章