php 从snippet商店循环woocommerce中删除重复

bakd9h0s  于 2023-01-24  发布在  PHP
关注(0)|答案(2)|浏览(116)

我的变量产品有两个属性:大小和颜色。当一些产品有属性M-〉红色,XL-〉蓝色,M-〉黄色。下面的代码片段显示属性M L M,这是确定的,但我找不到解决方案如何删除重复的项目

add_action('woocommerce_before_shop_loop_item_title', 'variations_loop');
function variations_loop() {
    global $product;
    if($product->get_type() == 'variable') {
        foreach($product->get_available_variations() as $key) {
            $variation = wc_get_product($key['variation_id']);
            echo $variation -> attributes['pa_size'];
        }
    }
}
hgqdbh6s

hgqdbh6s1#

根据您的注解,您似乎拥有以下数组:

[
    [
        "pa_size" => "m",
        "pa_color" => "blue"
    ],
    [
        "pa_size" => "xl",
        "pa_color" => "yellow"
    ],
    [
        "pa_size" => "m",
        "pa_color" => "blue"
    ]
]

您需要做的是调用array_map(documentation)来获取大小,调用array_unique(documentation)来获取唯一值。
一旦获得了这些唯一值,就可以选择使用array_filter(documentation)按大小获得乘积。
下面是一个例子:

// define the products
$products = [
    [
        "pa_size" => "m",
        "pa_color" => "blue"
    ],
    [
        "pa_size" => "xl",
        "pa_color" => "yellow"
    ],
    [
        "pa_size" => "m",
        "pa_color" => "blue"
    ]
];
// get just the "pa_size" values
$productSizes = array_map(function($key, $value) {
    return $value["pa_size"];
}, array_keys($products), array_values($products));
// get the unique "pa_size" values
$uniqueProductSizes = array_unique($productSizes);

// loop over the unique "pa_size" values
foreach ($uniqueProductSizes as $key => $value) {
    // get every product by the "pa_size"
    $productsBySize = array_filter($products, function($innerKey) use ($value) {
        return $value === $innerKey["pa_size"];
    });
}

小提琴:https://onlinephp.io/c/d637f

v6ylcynt

v6ylcynt2#

你的解决方案工作,但不适合我。我不知道哪里是问题。下面的片段和例子回应。

add_action( 'woocommerce_before_shop_loop_item_title', 'variations_loop' );
function variations_loop(){
    global $product;
    if ($product->get_type() == 'variable') {
        foreach($product->get_available_variations() as $key) {
            $variation = wc_get_product($key['variation_id']);      
            $varation_size = $variation -> attributes;      
            var_dump($varation_size);           
        }
    }
}

array(2) {
  ["pa_size"]=>
  string(1) "m"
  ["pa_color"]=>
  string(4) "blue"
}
array(2) {
  ["pa_size"]=>
  string(2) "xl"
  ["pa_color"]=>
  string(6) "yellow"
}
array(2) {
  ["pa_size"]=>
  string(1) "m"
  ["pa_color"]=>
  string(4) "blue"
}

相关问题