我需要根据产品的数量创建一个关联的数组。我如何将这一种衬里从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 %}
答案 0 :(得分:2)
您不能以与其他语言一样的方式创建数组。创建数组的唯一方法是在拆分字符串之后。
因此,您不能使用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: ',' %}
这就是为什么我们捕获输出并将其分割以创建数组的原因。