如何删除 Twig 上数组中的重复项 [英] How to remove duplicated items in array on Twig

查看:44
本文介绍了如何删除 Twig 上数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Twig 上删除数组中的重复项?

How to remove duplicated items in array on Twig?

我在树枝中有数组值,例如.

I have array value in twig such as.

{{ set array = ["testA","testB","testA","testC","testB"]  }}

我想删除重复项并仅使用 testA、testB、testC

I want to remove duplicated items and use only testA,testB,testC

{% for name in array%}

 //skip the duplicate items and use only testA,testB,testC

{% endfor %}

我该怎么做?

推荐答案

Twig 是一个 VIEW 引擎,理论上不应用于操作数据.使用(假设)PHP 来收集数据、执行所有必要的操作,然后将正确的数据传递给您的视图是一种(非常)好的做法.

Twig is a VIEW engine, and should not be used - in theory - to manipulate data. It's a (very) good practice to use (assumingly) PHP to gather data, do all necessary manipulations and then pass the right data to your view.

也就是说,您可以通过以下方式使用纯 Twig 语法进行操作:

That said, here's how you can do it in pure Twig syntax:

{% set newArray = [] %}

{% for name in array %}
   {% if name not in newArray %}
     My name is {{name}}
   {% set newArray = newArray|merge([name]) %}
   {% endif %}


{% endfor %}

这篇关于如何删除 Twig 上数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆