为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
冉冉说 2021-11-26 16:28:54
目前我有两个数组{% set code = [AMS, EIN, RTM] %} {% set city = [Amsterdam, Eindhoven, Rotterdam] %}我想检查{{airport}}第一个数组中是否存在的值,如果存在,code[0]我想更改{{airport}}为city[0]. 这可以用 Twig 实现吗?
查看完整描述

2 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

您可以遍历代码数组:


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


查看完整回答
反对 回复 2021-11-26
?
呼唤远方

TA贡献1856条经验 获得超11个赞

用于{% if value in array %}从第一个数组和 Twig 的合并函数中搜索以替换第二个数组中的值。请参阅此https://twig.symfony.com/doc/2.x/filters/merge.html


查看完整回答
反对 回复 2021-11-26
  • 2 回答
  • 0 关注
  • 164 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信