twig - 在 for 循环中构建数组
是否可以用值迭代填充树枝数组?
{% for question in questions %}
{% set multipleChoiceArray = [] %}
{% for multipleChoice in question.multipleChoiceAnswers %}
{% set multipleChoiceArray = multipleChoiceArray|merge( multipleChoice.answerText ) %}
{% endfor %}
{% endfor %}
问题就在这里multipleChoiceArray|merge(multipleChoice.answerText)
当我尝试传递一个数组时,例如键= loop.index,如
{% set multipleChoiceArray = multipleChoiceArray|merge({"loop['index']":"multipleChoice['answerText']"}) %}
它的工作原理,但数组包含字符串“[”loop['index']“:”multipleChoice['answerText']“]”
当我尝试传递变量时,例如:
{% set multipleChoiceArray = multipleChoiceArray|merge({loop.index:multipleChoice.answerText}) %}
例外是:哈希键后必须跟一个冒号(:)。值 “.(“标点符号”应为值“:”)
所以我无法将值“multipleChoice.answerText”“推”到“multipleChoiceArray”中
任何提示这怎么可能?我只想收集所有可能的答案,然后检查答案是否在该数组中,并计算sth并显示