Create a simple array in liquid

Viewed 2081

I need to make an associative array of products by their quantity. How do I convert this one liner from php to liquid

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

Best I came up was with this

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

You can't create arrays in the same way as other languages in liquid. The only way to create an array is after you split a string.

So you can't create an array item using product[item.product_id].

You first need to generate a String and then create the array by splitting that string.

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

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

That's why we capture the output and split it in order to create the array.

Related