1

我不确定为什么会这样,但我似乎经常遇到这个问题。这是我用于购物车的原始 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 的项目被删除时,它被结束时的结果是这样的:

{
    "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 个项目时,这让我感到困惑。有什么办法可以重写我的代码,以防止创建这些密钥?

4

2 回答 2

2

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

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

$_SESSION['cart_items']['cartitems'] = array_values($_SESSION['cart_items']['cartitems']);
于 2012-05-18T05:56:54.217 回答
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']);
于 2012-05-30T06:36:47.740 回答