在数组中查找值并从其他数组返回new

时间:2019-08-16 21:19:16

标签: php twig

目前我有两个数组

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

我想检查{{airport}}的值是否存在于第一个数组中,如果它是code[0],我想将{{airport}}更改为city[0]的值。 Twig有可能吗?

2 个答案:

答案 0 :(得分:1)

您可以遍历代码数组:

{% 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 %}

跑步小提琴:https://twigfiddle.com/xflfas/2

超出范围说明:您的数组最好命名为citiescodes
这样,当您遍历它们时,您将得到有意义的命名

{% set codes = ['AMS', 'EIN', 'RTM'] %} 
{% for code in codes %}
  {{ code }}
{% endfor %}

{# and #}

{% set cities = ['Amsterdam', 'Eindhoven', 'Rotterdam'] %} 
{% for city in cities %}
  {{ city }}
{% endfor %}

答案 1 :(得分:0)

使用{% if value in array %}从第一个数组中搜索,然后使用Twig的merge函数替换第二个数组中的值。看到这个https://twig.symfony.com/doc/2.x/filters/merge.html

相关问题