【问题标题】:Is there any alternative of PHP In_array() in Shopify?Shopify 中是否有 PHP In_array() 的替代方法?
【发布时间】:2019-07-01 08:44:47
【问题描述】:

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

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

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

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

在哪里

包,鞋子,xyz

是产品类型

和 2,3,6

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

我知道使用 PHP 很容易,但不知道如何使用 Shopify 液体代码。

【问题讨论】:

    标签: shopify liquid liquid-layout


    【解决方案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
    

    对于您在 cmets 中解释的特定场景,请查看以下代码和代码 cmets。我已使用 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-}}
    

    【讨论】:

    • 我想根据产品类型统计产品。意味着,在循环中,我想检查购物车中添加了多少具有相同产品类型的产品。即如果产品类型为 bag 的产品为 2,则 $array['bag'] = 2;如果 product_type "shoes" 的产品为 3,则 $array['shoes'] = 3;等等....那我怎么能贫血呢。不像你上面提到的那样是静态的。
    • 嘿@Bilal,你提出的想法很棒,对我来说效果很好。非常感谢。 +1 并被接受。
    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2023-03-21
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多