2016-12-23 160 views
1

我想比較array1_ids與客戶的購物車,如果數組的產品匹配那些在購物車領域x_name應該在那裏,如果不是它 應該消失。 我從我的購物車和array1_ids獲取值,但是當我將它們放入array_intersect時,它將導致NULL,從而導致它始終返回true。Array_intersect返回NULL

這裏是我的代碼:

function wc_ninja_product_is_in_the_cart() { 
/*array 1*/ 
$array1_ids = array('1', '3', '5');//field that should 
/*array 2*/ 
//$micro_ids = array('2', '4');//fields that shouldnt come back 

    // Products currently in the cart 
    $cart_ids = array(); 
    $cart_categories = array(); 

    // Find each product in the cart and add it to the $cart_ids array 
    foreach(WC()->cart->get_cart() as $cart_item_key => $values) { 
     $cart_product = $values['data']; 
     $cart_ids[] = $cart_product->id; 
    } 

    // If one of the special products are in the cart, return true. 
    if (! array_intersect($array1_ids, $cart_ids)) { 
     echo "true: " , implode(';',$cart_ids);;//bug fixing 
     return true; 
    } else { 
     return false; 
     echo "false: " , implode(';',$cart_ids);;//bug fixing 
    } 
} 
//Field Remover 
function wc_ninja_remove_checkout_field($fields) { 
    if (! wc_ninja_product_is_in_the_cart()) { 
     //removes Field x_name 
     unset($fields['billing']['x_name']); 
    } 
    return $fields; 
} 
add_filter('woocommerce_checkout_fields' , 'wc_ninja_remove_checkout_field'); 
+0

確定'$ card_ids'具有元素? – Jerodev

+0

一切都會返回值,除非通過array_intersect()運行它們() – user7329477

回答

1

這應該工作:

$hasSpecialProduct= false;  
foreach(WC()->cart->get_cart() as $cart_item_key => $values) { 
    $cart_product = $values['data']; 
    if (in_array($cart_product->id, $array1_ids)) { 
     $hasSpecialProduct = true; 
    } 
    $cart_ids[] = $cart_product->id; 
} 

// If one of the special products are in the cart, return true. 
if ($hasSpecialProduct) { 
    echo "true: " , implode(';',$cart_ids);;//bug fixing 
    return true; 
} else { 
    return false; 
} 

可以使最後部分短:

return $hasSpecialProduct; 
+1

非常感謝您的工作!我無法贊成,因爲我是堆棧溢出的新手,但無論如何感謝。無論如何,我已經接受你的答案。 – user7329477