我遇到了一個有點惱人的問題。這是我的PHP代碼。忽略變量來自哪裏。這是爲了購物車的功能,但它適用於許多不同的領域。將值推入數組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在前端?
對不起,我有這麼多的問題。任何幫助真的很感激。
你想要它看起來像什麼? – deceze