首页 > 解决方案 > 在液体中创建一个简单的数组

问题描述

我需要按数量制作一个关联的产品数组。如何将这一衬里从 php 转换为液体

foreach(items as item) $product[$item.product_id] += $item.quantity

我想出的最好的就是这个

{% for item in cart.items %}
    {% assign product[item.product_id] = 0 | plus product[item.product_id] | plus item.quantity %}
{% endfor %}

标签: phpshopifyliquid

解决方案


您不能像在液体中使用其他语言一样创建数组。创建数组的唯一方法是在拆分字符串之后。

所以你不能使用product[item.product_id].

您首先需要生成一个字符串,然后通过拆分该字符串来创建数组。

{%- capture items -%}
    {%- for line_item in cart.items -%}
        {{- line_item.product_id -}}|{{-line_item.quantity-}},
    {%- endfor -%}
{%- endcapture -%}

{% assign items_array = items | split: ',' %}

这就是我们捕获输出并将其拆分以创建数组的原因。


推荐阅读