php 树枝 - 在 for 循环中构建数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20841206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
twig - building array in for loop
提问by john Smith
is it possible to iteratively fill a twig array with values?
是否可以用值迭代地填充树枝数组?
{% for question in questions %}
{% set multipleChoiceArray = [] %}
{% for multipleChoice in question.multipleChoiceAnswers %}
{% set multipleChoiceArray = multipleChoiceArray|merge( multipleChoice.answerText ) %}
{% endfor %}
{% endfor %}
the problem is here multipleChoiceArray|merge(multipleChoice.answerText)
问题就在这里 multipleChoiceArray|merge(multipleChoice.answerText)
when i try to pass an array for example with key = loop.index like
当我尝试传递一个数组时,例如 key = loop.index like
{% set multipleChoiceArray = multipleChoiceArray|merge({"loop['index']":"multipleChoice['answerText']"}) %}
it works but the array contains the strings "["loop['index']":"multipleChoice['answerText']"]"
它有效,但数组包含字符串 "["loop['index']":"multipleChoice['answerText']"]"
when i try to pass variables like :
当我尝试传递如下变量时:
{% set multipleChoiceArray = multipleChoiceArray|merge({loop.index:multipleChoice.answerText}) %}
exception is : A hash key must be followed by a colon (:). Unexpected token "punctuation" of value "." ("punctuation" expected with value ":")
例外是:散列键后面必须跟一个冒号 (:)。值“.”的意外标记“标点符号”。(“标点符号”预期值为“:”)
so i am not able to "push" a value "multipleChoice.answerText" into "multipleChoiceArray"
所以我无法将值“multipleChoice.answerText”“推”到“multipleChoiceArray”中
any hints how that is possible ? i just want to gather all possible answers and later check if answer is in that array and count sth up and display
任何提示怎么可能?我只想收集所有可能的答案,然后检查答案是否在该数组中并计算并显示
回答by Markus Kottl?nder
The argument of merge has to be an array or object to merge it with an existing one. So write it as an array with one element.
merge 的参数必须是一个数组或对象才能将其与现有的合并。所以把它写成一个只有一个元素的数组。
{% set multipleChoiceAnswerText = multipleChoice.answerText %}
{% set multipleChoiceArray = multipleChoiceArray|merge([multipleChoice.answerText]) %}

