如果至少有一个项在数组中且一个不是

时间:2017-07-13 12:44:42

标签: php arrays wordpress woocommerce

我需要为这个if语句返回true,如果至少有一个项在数组中,而一个不在数组中,并且不确定如何编写它。

这当然有效,但如果所有项目都在数组中或者所有项目都不在数组中,我需要返回false。

$shipping_classes = array( 50, 100, 150, 200, 250, 300 );
$cart_items = WC()->cart->get_cart();
$cart_items_count = WC()->cart->get_cart_contents_count();
$items_match = false;

foreach( $cart_items as $cart_item )
    if( in_array( $cart_item[ 'data' ]->get_shipping_class(), $shipping_classes ) && $cart_items_count > 1 || !in_array( $cart_item[ 'data' ]->get_shipping_class(), $shipping_classes ) && $cart_items_count > 1 ) {
        $items_match = true;
        break; // Stop the loop
    }

2 个答案:

答案 0 :(得分:2)

只计算找到/未找到某些内容的次数,然后在最后进行比较?

<?php 
    $shipping_classes = array( 50, 100, 150, 200, 250, 300 );
    $cart_items = WC()->cart->get_cart();
    $cart_items_count = WC()->cart->get_cart_contents_count();

    $items_match = false;

    $inArray    = 0;
    $notInArray = 0;


    foreach( $cart_items as $cart_item ){
        if( in_array( $cart_item[ 'data' ]->get_shipping_class(), $shipping_classes ) && $cart_items_count > 1 || !in_array( $cart_item[ 'data' ]->get_shipping_class(), $shipping_classes ) && $cart_items_count > 1 ) {
            $inArray++;
        } else { 
            $notInArray++;
        }
    }
    if( ( $cart_items_count == $notInArray ) || ( $cart_items_count == $inArray ) ){
        $items_match = false;
    } else { 
        $items_match = true;
    }

答案 1 :(得分:0)

如何从构建数组的代码中解析检查数组是否存在于另一个数组中的代码?例如:

function allOrNoneInArray($search, $array)
{
    $diff  = array_diff($search, $array);
    $ndiff = count($diff);

    return $ndiff === 0 || $ndiff === count($search);
}

$shipping_classes = array(50, 100, 150, 200, 250, 300);
$items_shipping_classes = array();
foreach($cart_items as $cart_item) {
    $items_shipping_classes[] = $cart_item[ 'data' ]->get_shipping_class();
}

if (allOrNoneInArray($items_shipping_classes, $shipping_classes)) {
    // add code here
}