【问题标题】:Array_intersect returns NULLArray_intersect 返回 NULL
【发布时间】:2017-05-09 07:00:37
【问题描述】:

如果数组的产品与购物车字段中的产品匹配,我正在尝试将 array1_ids 与客户的购物车进行比较 应该消失了。 我从我的购物车和 array1_ids 中获取值,但是当我将它们放入 array_intersect 时,它会导致 NULL 导致它始终返回 true。

这是我的代码:

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' ); 

【问题讨论】:

  • 你确定$card_ids 有元素吗?
  • 一切都返回值,除非你通过 array_intersect() 运行它们

标签: php woocommerce array-intersect


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

【讨论】:

  • 非常感谢您的成功!我不能投票,因为我是堆栈溢出的新手,但无论如何谢谢。反正我已经接受了你的回答。
猜你喜欢
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 2020-06-19
  • 2011-10-15
相关资源
最近更新 更多