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 循环中构建数组
基础教程推荐
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01