在数组中查找值并从不同数组返回新值

目前我有两个数组

{% set code = [AMS, EIN, RTM] %}
{% set city = [Amsterdam, Eindhoven, Rotterdam] %}

我想检查{{airport}}第一个数组中是否存在的值,如果存在,code[0]我想更改{{airport}}city[0]. 这可以用 Twig 实现吗?


冉冉说
浏览 165回答 2
2回答

皈依舞

您可以遍历代码数组:{% 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在相同的循环索引处替换变量 airport:{# ... #}{% 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 %}运行小提琴: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
打开App,查看更多内容
随时随地看视频慕课网APP