Twig 比较不同数组中的两个值

Twig compare two values in different arrays

首先,我正在学习 Twig。 我想知道是否可以使用 Twig 比较来自不同 arrays/lists 的两个不同值?!

我有两个项目列表,我这样称呼它们:

{% if page.cart %}
{% for product in page.cart.products %}
  {{ product.id }}
{% endfor %}
{% endif %}

并且:

{% if products %}
{% for product in products %}
  {{ product.id }}
{% endfor %}
{% endif %}

我想比较两个 product.id,这样我就可以创建一个新的语句。有没有办法比较这两个值?这个想法是检查 page.cart.products 中是否存在 id,如果存在则执行某些操作。

我想创建一个新语句来显示一些信息。像这样:

{% if page.cart %}
{% for product in page.cart.products %}
  {% set cartId %}{{ product.id }}{% endset %}
{% endfor %}
{% endif %}

{% if products %}
{% for product in products %}
  {% set listId %}{{ product.id }}{% endset %}
{% endfor %}
{% endif %}

{% if cartId == listId %}
.... do this ....
{% endif %} 

非常感谢任何帮助!

您可以遍历一个数组并检查 id 是否出现在第二个数组中。如果它在那里,你可以做点什么。

{# In case you want to store them, you can do so in an array #}
{% set repeatedIds = [] %}
{% for productCart in page.cart.products if page.cart %}
    {% for product in products if products %}
        {% if productCart.id == product.id %}
            <p>This id -> {{ product.id }} is already in page.cart.products</p>
            {% set repeatedIds = repeatedIds|merge([product.id]) %}
        {% endif %}
    {% endfor %}
{% endfor %}
{{ dump(repeatedIds) }}

这是一个非常基本的搜索算法,成本是二次方的。显然,有更有效的方法来查找数组中的元素(尽管实现起来更复杂)。

如果您要处理的产品量不是很大,可以使用这个方案。但是,假设每个数组中有超过 100 个产品(或者您觉得该算法正在减慢您的加载时间),您可以在控制器中使用更复杂的方法和 PHP并将结果传递给模板。

希望对您有所帮助。