twig - building array in for loop(twig - 在 for 循环中构建数组)
问题描述
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)
when i try to pass an array for example with key = loop.index like
{% set multipleChoiceArray = multipleChoiceArray|merge({"loop['index']":"multipleChoice['answerText']"}) %}
it works but the array contains the strings "["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"
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
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.
{% set multipleChoiceAnswerText = multipleChoice.answerText %}
{% set multipleChoiceArray = multipleChoiceArray|merge([multipleChoice.answerText]) %}
这篇关于twig - 在 for 循环中构建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:twig - 在 for 循环中构建数组


基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01