在液体中创建一个简单的数组

Sae*_*kar 2 php liquid shopify

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

foreach(items as item) $product[$item.product_id] += $item.quantity
Run Code Online (Sandbox Code Playgroud)

我想到的最好的就是这个

{% for item in cart.items %}
    {% assign product[item.product_id] = 0 | plus product[item.product_id] | plus item.quantity %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

dri*_*rip 5

你不能像在 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: ',' %}
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢。知道了。液体是如此混乱 (6认同)