我正在尝试循环保存数组的Php变量。我想在for循环var
的键中传递变量假设看起来像这样:
{% set fields_vars =["dogs","cats","birds"] %}
{% set foo = 123 %}
<select id="my_filter_1" class=" form-control filters_space filter">
// my_filter needs to be increment automatically
{% for fields_var in fields_vars %}
<option >{{ fields_vars [ foo //pass twig variable as key// ]}}</option>
{% endfor %}
</select>
我无法获得将变量作为键传递的正确语法 - 我尝试过:
<option >{{ fields_vars [ foo ]}}</option> // Error
<option >{{ fields_vars [{{ foo }} ]}}</option> // Error
<option >{{ fields_vars ['.'{{ foo }}'.' ]}}</option> // Error
谢谢:)
答案 0 :(得分:0)
语法为fields_vars [ foo ]
。我在网上ifddle上给你一个例子
小提琴:https://twigfiddle.com/tdau2h
{% set fields_vars =["dogs","cats","birds"] %}
{% set foo = 123 %}
{# value #}
{% if foo in fields_vars %}
{{ foo }} is in array {{ fields_vars|join(', ') }}
{% else %}
{{ foo }} is not in array {{ fields_vars|join(', ') }}
{% endif %}
{# key #}
{% if fields_vars[foo] is defined %}
key {{ foo }} is in array {{ fields_vars|join(', ') }}
{% else %}
key {{ foo }} is not in array {{ fields_vars|join(', ') }}
{% endif %}