我需要按产品的数量创建一个关联数组。如何将这一衬垫从 php 转换为 Liquid
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 %}
最佳答案
你不能像在 Liquid 中的其他语言一样创建数组。创建数组的唯一方法是在拆分字符串之后。
因此您无法使用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: ',' %}
这就是我们捕获输出并将其分割以创建数组的原因。
关于php - 在液体中创建一个简单的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63899716/