我不知道为什么会发生这种情况,但我似乎经常遇到这个问题。这里是我的购物车原有的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个项目时才会发生,这会让我感到困惑。有什么办法可以重写我的代码,以防止创建这些密钥?
http://codepad.org/NXLF00eg - 无法重现 –
我觉得@杰克的代码是他在做之前做了'json_decode'的answer..as一个'foreach'。 –
顺便说一句,你确定还要做一个'echo json_encode($ _ SESSION ['cart_items']);'*之前*修改数组? –