从php中的for循环迭代中提取整数


Extracting integer from a for loop iteration in php, twig

我目前正在php(trick模板(中迭代数据数组。

{% for subscription in form.peerEventSubscriptions %}
<option value='{{typeDefEvent[0]}}'>-{{ form_label(subscription.eventTypeHumanized) }}-</option>
{% endfor %}

数据只是文本。是否可以同时获取一个整数来更新数组索引:

typeDefEvent[i]

谢谢并记住,这是一个树枝模板。

这里没有必要引入另一个变量。引用文档

for循环块内部,您可以访问一些特殊变量:

Variable        Description
loop.index      The current iteration of the loop. (1 indexed)
loop.index0     The current iteration of the loop. (0 indexed)
loop.revindex   The number of iterations from the end of the loop (1 indexed)
loop.revindex0  The number of iterations from the end of the loop (0 indexed)
loop.first      True if first iteration
loop.last       True if last iteration
loop.length     The number of items in the sequence
loop.parent     The parent context

所以你可以这样写你的模板:

{% for subscription in form.peerEventSubscriptions %}
  <option value='{{typeDefEvent[loop.index0]}}'>-{{ form_label(subscription.eventTypeHumanized) }}-</option>
{% endfor %}
{% set i = 0 %}
   <select name="myPostVar">
{% for subscription in form.peerEventSubscriptions%}
<option value='{{typeDefEvent[i]}}'>-{{ form_label(subscription.eventTypeHumanized) }}-</option>
{% set i = i+1 %}
{% endfor %}

基本上使用模板标签

在循环中设置和更新迭代器