0

我遇到了一个有点烦人的问题。这是我的PHP代码。忽略变量的来源。这适用于购物车功能,但它适用于许多不同的领域。

$data_set = json_decode(stripslashes($_POST['varA']), true);
$pid = $pid['product_id'];
$quantity = $pid['quantity'];

$_SESSION['cartid'] = $_SESSION['cartid'] + 1;

$product_data = array("Product_ID" = > $pid, "quantity" = > $quantity, "cartid" = > $_SESSION['cartid']);

我的问题发生在代码中的这个地方。我首先检查 Session 变量中是否有值,如果没有,则继续创建关联数组。

if (empty($_SESSION['cart_items'])) {
    $_SESSION['cart_items'] = array("items" = > $product_data);
} else {
    array_push($_SESSION['cart_items']['items'], $product_data);
}


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

“添加”第一项后的最终结果如下所示:

{
    "items": {
        "Product_ID": "2",
        "quantity": "1",
        "cartid": 1
    }
}

但是,经过几次第一次添加后,每个值都会得到一个键:

{
    "items": {
        "0": {
            "Product_ID": "2",
            "quantity": "1",
            "cartid": 2
        },
        "1": {
            "Product_ID": "2",
            "quantity": "1",
            "cartid": 3
        },
        "Product_ID": "2",
        "quantity": "1",
        "cartid": 1
    }
}

如何防止这些键出现?这可能吗?如果没有,如何重新编写以便每次都添加密钥?这是否可以在前端的 JS 中解析和循环?

对不起,我有很多问题。非常感谢任何帮助。

4

3 回答 3

1

In the first iteration, the $_SESSION['cart_items'] is empty, so you run this:

$_SESSION['cart_items'] = array("items" => $product_data);

This creates $_SESSION['cart_items']['items'] but you populate it with just the product by itself; you should define it as an array instead:

$_SESSION['cart_items'] = array("items" => array($product_data));

This creates an array with a single item which you can later extend with array_push.

Having said that, you can replace the whole condition with just:

$_SESSION['cart_items']['items'][] = $product_date;

PHP will automatically create an empty array if it didn't exist yet, followed by adding the product data as the next element.

于 2012-05-17T06:42:14.193 回答
0

You don't need the items, try the below way.

if (empty($_SESSION['cart_items'])) {
    $_SESSION['cart_items'] = array($product_data);
} else {
    $_SESSION['cart_items'][] = $product_data;
}
于 2012-05-17T06:40:02.493 回答
0

这是因为这一行:

$_SESSION['cart_items'] = array("items" = > $product_data);

您基本上在该行中说“项目”键具有产品数据,而不是项目中的键。它应该是:

$_SESSION['cart_items']['items'] = array($product_data);

键 - 将 - 总是出现,除非您希望数据覆盖另一个。如果您不想要键(0,1 等),那么唯一的其他选择是合并数据。在这种情况下,它将是:

$_SESSION['cart_items']['items']+=$product_data;

..但我不认为那是你想要的。

于 2012-05-17T06:36:53.963 回答