Shopify中是否可以使用PHP In_array()?

时间:2019-07-01 08:44:47

标签: shopify liquid liquid-layout shopify-cart

我尝试了很多事情,但没有得到我想要的东西。

下面是我在Shopify中寻找哪种类型的数组的示例,

  

$ array ['bag'] = 2; $ array ['shoes'] = 3; $ array ['xyz'] = 6;

这是我在shopify中寻找数组变量的方式和方式的示例。

哪里

  

包,鞋,xyz

是产品类型

  

和2,3,6

是为特定产品类型添加的产品数量。

我知道它在PHP中很容易,但是不知道在Shopify临时代码中该如何做。

请问任何一个能帮助我的人!

1 个答案:

答案 0 :(得分:1)

根据Shopify documentation,您无法初始化数组。但是,您可以使用split filter创建一维数组。您不能使用此方法创建关联数组。但是,作为一种解决方法,请使用2个长度相同的数组,其中两个数组中的相同索引都指向关联数组的相关键和值。示例代码

  {% assign product_type = "type-1|type-2|type-3" | split: '|' %}
  {% assign product_count = "1|2|3" | split: '|' %}


    {% for p_type in product_type %}
        {{ p_type }}
        {{ product_count[forloop.index0] }}
    {% endfor %}

预期产量

Product Type   Count
type-1           1
type-2           2
type-3           3

对于注释中说明的特定情况,请查看下面的代码和代码注释。我已经使用checkout object作为示例代码。您可以根据需要进行调整。

// declare 2 vars to create strings - that will be converted to arrays later
{% assign product_type = "" %}
{% assign product_count = "" %}

// iterate over line_items in checkout to build product_type string
{% for line_tem in checkout.line_items %}
  // if product_type exists , then skip -- unique product types
  {% if product_type contains line_tem.product.type%}
  {% else %}
    {% assign product_type = product_type | append: '#' | append: line_tem.product.type %}   
  {% endif %}

{% endfor %}

// remove first extra hash and convert to array
{% assign product_type = product_type | remove_first: "#" | split: '#' %}


// iterate over unique product type array generated earlier
{% for product_type_item in product_type %}
// set product count for this product type to zero initially
{% assign total_count = 0 %}
// iterate over all lin items and +1 if same product type
  {% for line_tem in checkout.line_items %}
    {% if product_type_item == line_tem.product.type%}
      {% assign total_count = total_count | plus: 1 %} 
    {% endif %}
  {% endfor %}
  // append count to product count string
  {% assign product_count = product_count | append: '#' | append: total_count %}
{% endfor %}

// remove first extra hash and convert to array
{% assign product_count = product_count | remove_first: "#" | split: '#'%}

{{-product_type-}}

{{-product_count-}}
相关问题