2012-05-18 36 views
1

我不知道为什么会发生这种情况,但我似乎经常遇到这个问题。这里是我的购物车原有的JSON:PHP增加了解码后的密钥,然后编码JSON数据

{ 
    "cartitems": [ 
     { 
      "Product_ID": "1", 
      "quantity": "1", 
      "cartid": 1 
     }, 
     { 
      "Product_ID": "5", 
      "quantity": "1", 
      "cartid": 4 
     }, 
     { 
      "Product_ID": "5", 
      "quantity": "1", 
      "cartid": 6 
     }, 
     { 
      "Product_ID": "5", 
      "quantity": "1", 
      "cartid": 7 
     } 
    ] 
} 

这JSON数据存储到$ _SESSION变量$ _SESSION [“cart_items”]

此代码是用来删除项目:

$cartid = $_POST['varA']; 

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


echo json_encode($_SESSION['cart_items']); 

当与cartid项= 7被除去,结果是这样的,当它被endoded:

{ 
    "cartitems": { 
     "0": { 
      "Product_ID": "1", 
      "quantity": "1", 
      "cartid": 1 
     }, 
     "1": { 
      "Product_ID": "5", 
      "quantity": "1", 
      "cartid": 4 
     }, 
     "2": { 
      "Product_ID": "5", 
      "quantity": "1", 
      "cartid": 6 
     } 
    } 
} 

它增加了钥匙!这只有当有超过3个项目时才会发生,这会让我感到困惑。有什么办法可以重写我的代码,以防止创建这些密钥?

+1

http://codepad.org/NXLF00eg - 无法重现 –

+0

我觉得@杰克的代码是他在做之前做了'json_decode'的answer..as一个'foreach'。 –

+0

顺便说一句,你确定还要做一个'echo json_encode($ _ SESSION ['cart_items']);'*之前*修改数组? –

回答

2

在PHP中,只有数组用于关联和数字索引的映射/列表/数组。 Javascript/JSON有两个不同的概念:数字索引数组([...])和对象映射({ foo : ... })。对于json_encode来决定编码数组时要使用哪一种,幕后有一些逻辑。通常,如果数组键是连续的并且都是数字,则该数组将被编码为JSON数组([...])。如果甚至有一个按键失序或非数字键,则使用JSON对象代替。

为什么你的数组操作特别会触发一个对象,我不知道。为了避免这种情况,虽然,您可以重置数组键,以确保它们是数字,连续索引:

$_SESSION['cart_items']['cartitems'] = array_values($_SESSION['cart_items']['cartitems']); 
+0

是的,这非常有意义。但是,当我重置数组,因为你已经把它,我得到这个错误:为foreach() – TaylorMac

+0

确定提供的无效参数。我的坏它不会给出这个错误。但是,它似乎没有解决这个问题。我相信这是正确的方法,我只是不知道为什么它仍然作为一个对象后操纵 – TaylorMac

0

试试这个,为我工作。 阵列,支持自动密钥传送到一个新的数组:

/* 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']);