未定义的偏移量:0-Ajax响应中的PHP错误

时间:2018-08-30 15:30:34

标签: php wordpress undefined-index

我确信这是一个简单的修复程序,但是我似乎无法弄清楚。错误是Undefined offset: 0

我的代码实际可用,但是在浏览器控制台中出现此错误。我尝试查看此答案enter image description here并声明该变量,但是它仍在触发错误。我缺少明显的东西吗?

我尝试通过添加$product_id= $_POST['id'] ?? '';$product_id = 0;来声明,但是它们似乎没有任何变化。

有人可以帮助我吗?

    function checking_items() {
    if( isset($_POST['id']) && $_POST['id'] > 0 ){
        // Initialising variables
        $counts     = array();
        $product_id = $_POST['id'];
        $categories = array('protein', 'pantry');

        // Loop through cart for product categories count
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( has_term( $categories[0], 'product_cat', $cart_item['product_id'] ) )
               $counts[0] += $cart_item['quantity'];
            if ( has_term( $categories[1], 'product_cat', $cart_item['product_id'] ) )
               $counts[1] += $cart_item['quantity'];
        }

        // Return the product category count that belongs to the added item
        if( has_term( $categories[0], 'product_cat', $product_id ) )
            echo json_encode(array(strtoupper($categories[0]) => $counts[0])); // Returned value to jQuery
        if( has_term( $categories[1], 'product_cat', $product_id ) )
            echo json_encode(array(strtoupper($categories[1]) => $counts[1])); // Returned value to jQuery
    }

    die(); // To avoid server error 500
}

{{3}}

1 个答案:

答案 0 :(得分:1)

您需要以以下方式正确启动$counts

$counts = array(0,0);

因为您当前正在尝试增加不存在的位置:

// This doesn't work when position zero doesn't exist.
$counts[0] += $cart_item['quantity'];

同样的情况适用于您的$counts[1] +=行。