亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在數組中查找值并從不同數組返回新值

在數組中查找值并從不同數組返回新值

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 關注
  • 188 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號