PHP adds keys to decoded and then encoded JSON data

后端 未结 2 864
醉酒成梦
醉酒成梦 2020-12-04 03:22

I\'m not sure why this is happening, but I seem to run into this problem often. Here is my original JSON for a shopping cart:

{
    \"cartitems\": [
                 


        
2条回答
  •  误落风尘
    2020-12-04 04:12

    Try this, worked for me. Transfer the array to a new array with auto keys:

    /* Remove the item */
    foreach ($_SESSION['cart_items']['cartitems'] as $key => $product) {
        if ($product['cartid'] == $cartid) {
            unset($_SESSION['cart_items']['cartitems'][$key]);
        }
    }
    $var=array();
    foreach($_SESSION['cart_items']['cartitems'] as $key => $product) {
            $var['cart_items']['cartitems'][] = $product;
    }
    echo json_encode($var['cart_items']);
    

提交回复
热议问题