WooCommerce:如果另一个属性是循环的一部分,则跳过 foreach 中的属性

WooCommerce: Skip attribute in foreach if anotner attribute is part of the loop

我在我的产品页面上显示了属性(颜色)列表。

该列表包含许多类似的属性,如“蓝色”、“淡蓝色”、“海洋”等。 为了使 attributes/colors 的列表简短,如果“blue”是循环的一部分,我想删除每个版本的 blue。

这是我的循环代码:

<?php
global $product;
$pa_colors = wc_get_product_terms( $product->get_id(), 'pa_colors', array( 'fields' =>  'all', 'orderby' => 'menu_order' ) );
if( $pa_colors ) :
?>
    <ul>
        <?php foreach ( $pa_colors as $pa_color ) : ?>
        <li>
            <?php echo $pa_color->name; ?>
        </li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>

我知道,如果里面有颜色“蓝色”,我可以用这样的东西检查循环:

$color_blue = $product->get_attribute('pa_colors');

// Check if blue is in the attribute array:
if( strpos($color_blue, 'blue') !== false ) :

// Versions of blue to remove
$color_blue_versions = array('light blue', 'marine')

但是我怎么能从 foreach 循环中跳过 $color_blue_versions 中所有其他版本的蓝色呢?

您可能正在寻找 array_diff()

Computes the difference of arrays.

这是一个最小的例子。

<?php
$colors = [ 'blue', 'light-blue', 'sea-blue', 'murmaid-blue', 'green', 'yellow', 'red', ];
$exclude = [ 'light-blue', 'sea-blue', 'murmaid-blue', ];
$colors = array_diff( $colors, $exclude );
print_r( $colors ); ?>