使用来自不同数组的新值在数组和 return 中查找值
Find value in array and return with new from different array
目前我有两个数组
{% set code = [AMS, EIN, RTM] %}
{% set city = [Amsterdam, Eindhoven, Rotterdam] %}
我想检查第一个数组中是否存在 {{airport}}
的值,如果是 code[0]
我想将 {{airport}}
的值更改为 city[0]
. Twig 可以吗?
你可以遍历代码数组:
{% for c in code %}
{# ... #}
{% endfor %}
文档: https://twig.symfony.com/doc/2.x/tags/for.html
然后如果该项目确实匹配:
{# ... #}
{% if airport == c %}
{# ... #}
{% endif %}
{# ... #}
文档: https://twig.symfony.com/doc/2.x/tags/if.html
在相同的循环索引处替换变量机场:
{# ... #}
{% set airport = city[loop.index0] %}
{# ... #}
文档: https://twig.symfony.com/doc/2.x/tags/for.html#the-loop-variable
所以,完整的:
{% for c in code %}
{% if airport == c %}
{% set airport = city[loop. index0] %}
{% endif %}
{% endfor %}
运行 fiddle: https://twigfiddle.com/xflfas/2
超出范围注意事项:您的数组最好命名为 cities
和 codes
.
这样,当你遍历它们时,你最终会得到有意义的命名
{% set codes = ['AMS', 'EIN', 'RTM'] %}
{% for code in codes %}
{{ code }}
{% endfor %}
{# and #}
{% set cities = ['Amsterdam', 'Eindhoven', 'Rotterdam'] %}
{% for city in cities %}
{{ city }}
{% endfor %}
使用{% if value in array %}
从第一个数组开始搜索,使用Twig的合并函数替换第二个数组中的值。看到这个 https://twig.symfony.com/doc/2.x/filters/merge.html
目前我有两个数组
{% set code = [AMS, EIN, RTM] %}
{% set city = [Amsterdam, Eindhoven, Rotterdam] %}
我想检查第一个数组中是否存在 {{airport}}
的值,如果是 code[0]
我想将 {{airport}}
的值更改为 city[0]
. Twig 可以吗?
你可以遍历代码数组:
{% for c in code %}
{# ... #}
{% endfor %}
文档: https://twig.symfony.com/doc/2.x/tags/for.html
然后如果该项目确实匹配:
{# ... #}
{% if airport == c %}
{# ... #}
{% endif %}
{# ... #}
文档: https://twig.symfony.com/doc/2.x/tags/if.html
在相同的循环索引处替换变量机场:
{# ... #}
{% set airport = city[loop.index0] %}
{# ... #}
文档: https://twig.symfony.com/doc/2.x/tags/for.html#the-loop-variable
所以,完整的:
{% for c in code %}
{% if airport == c %}
{% set airport = city[loop. index0] %}
{% endif %}
{% endfor %}
运行 fiddle: https://twigfiddle.com/xflfas/2
超出范围注意事项:您的数组最好命名为 cities
和 codes
.
这样,当你遍历它们时,你最终会得到有意义的命名
{% set codes = ['AMS', 'EIN', 'RTM'] %}
{% for code in codes %}
{{ code }}
{% endfor %}
{# and #}
{% set cities = ['Amsterdam', 'Eindhoven', 'Rotterdam'] %}
{% for city in cities %}
{{ city }}
{% endfor %}
使用{% if value in array %}
从第一个数组开始搜索,使用Twig的合并函数替换第二个数组中的值。看到这个 https://twig.symfony.com/doc/2.x/filters/merge.html