<?php
session_start();
$pid = $_GET['pid'];
$ptype = $_GET['ptype'];
$_SESSION = array();
$_SESSION['cart_items'] = array();
if (isset($_GET['add_cart']) && !empty($_GET['add_cart'])) {
// Add new data to Session var
$newdata = array($pid , $ptype, 1 );
array_push($_SESSION['cart_items'], $newdata);
}
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
?>
array_push
将$_SESSION
中已有的数据替换为$_SESSION
中的$newdata
变量,而不是将其添加。
例如:
我输入网址:?pid=1&ptype=CH-&add_cart=Add+to+Cart
数组看起来像这样:
array(1) {
["cart_items"]=>
array(1) {
[0]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(3) "CH-"
[2]=>
int(1)
}
}
}
真棒。但是当我输入另一个网址时,例如:?pid=1&ptype=CPU-&add_cart=Add+to+Cart
数组如下所示:
array(1) {
["cart_items"]=>
array(1) {
[0]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(4) "CPU-"
[2]=>
int(1)
}
}
}
取而代之的是:
array(1) {
["cart_items"]=>
array(1) {
[0]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(3) "CH-"
[2]=>
int(1)
}
[1]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(4) "CPU-"
[2]=>
int(1)
}
}
}
它将替换会话中已有的数据。我希望它添加到它。我该怎么做?
提前感谢!
将第 5 行和第 6 行从
$_SESSION = array();
$_SESSION['cart_items'] = array();
自
// $_SESSION = array();
// $_SESSION['cart_items'] = array();
array_push没有清除您的数据。 这两行在每次页面加载时清除会话数据。