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

Undefined offset: 0 - PHP Errors in Ajax Response

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

我的代码确实有效,但在浏览器控制台中出现此错误。我试过查看此答案 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
}

您需要正确启动 $counts 作为:

$counts = array(0,0);

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

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

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