PHP 将密钥添加到解码然后编码的 JSON 数据中


PHP adds keys to decoded and then encoded JSON data

我不确定为什么会发生这种情况,但我似乎经常遇到这个问题。这是我购物车的原始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 个项目时,这让我感到困惑。有什么方法可以重写我的代码,以防止创建这些密钥?

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

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

连续索引:
$_SESSION['cart_items']['cartitems'] = array_values($_SESSION['cart_items']['cartitems']);

试试这个,为我工作。使用自动键将阵列传输到新阵列:

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