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

问题描述 投票:-3回答:1

我相信这是一个简单的解决方案,但我似乎无法弄明白。错误是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
}

enter image description here

php wordpress undefined-index
1个回答
1
投票

您需要正确启动$counts

$counts = array(0,0);

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

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

同样的事情适用于你的$counts[1] +=线。

© www.soinside.com 2019 - 2024. All rights reserved.