在PHP会话中存储对象数组
如何在PHP会话中存储/删除/获取对象数组 我尝试这样做是为了添加:在PHP会话中存储对象数组,php,session,session-variables,Php,Session,Session Variables,如何在PHP会话中存储/删除/获取对象数组 我尝试这样做是为了添加: array_push($_SESSION['cart'], serialize($item)); 这是为了删除: function removeitem ($item) { $arrayCart = $_SESSION['cart'] ; for ($i=0; $i<$arrayCart.length; $++ ) { if ($item.id == $arrayCart
array_push($_SESSION['cart'], serialize($item));
这是为了删除:
function removeitem ($item)
{
$arrayCart = $_SESSION['cart'] ;
for ($i=0; $i<$arrayCart.length; $++ )
{
if ($item.id == $arrayCart[i].id)
$arrayCart.splice (i,0);
}
}
函数删除项($item)
{
$arrayCart=$\会话['cart'];
对于($i=0;$i您是否尝试过使用此选项
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
$_SESSION['cart'][] = $item;
您不需要序列化item变量-会话可以存储纯对象,只要最大会话大小不超过
如果你想从购物车中删除商品,你应该使用索引名——这可以让你更快地找到你的商品
我可能会用这样的方式:
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
function addItem($itemName){
if(!isset($_SESSION['cart'][$itemName])) {
$_SESSION['cart'][$itemName] = 1;
}else
$_SESSION['cart'][$itemName] ++;
}
}
function removeItem($itemName){
if(isset($_SESSION['cart'][$itemName])) {
if($_SESSION['cart'][$itemName] > 0) {
$_SESSION['cart'][$itemName] --;
}
}
}
function clearCart(){
unset($_SESSION['cart']);
}
function removeitem ($item){
$arrayCart = $_SESSION['cart'] ;
for ($i=0; $i<$arrayCart.length; $++ ){
if ($item.id == $arrayCart[i].id){
$arrayCart.splice (i,0);
}
}
}
在这种情况下,购物车存储每个项目及其金额。您也可以使用数据库中的项目ID,而不是$itemName
要从购物车中获取商品,您需要此功能:
function getItemCount($itemName){
if(isset($_SESSION['cart'][$itemName])) {
return $_SESSION['cart'][$itemName];
}
return 0;
}
尝试不推送到数组,因为它可能尚未设置,但要存储到会话,请通过以下方式创建新的会话变量:
$_SESSION['cart']=serialize($item);
要删除它,请执行以下操作:
unset($_SESSION['cart']);
编辑:
由于注释,我意识到上面的代码不会在会话中存储数组。因此,另一个简短的解决方案是将一些JSON存储到会话var。请尝试以下简短测试:
$tmp = array(1,2,3);
$_SESSION['cart']=json_encode($tmp);
print_r(json_decode($_SESSION['cart']));
如果该数组是关联的,则应使用以下命令进行解码:
json_decode($_SESSION['cart'], true);
删除
这是我的工作…
如果此代码报告错误,请评论以检查此。。。
请检查PHP版本如何没有人看到这一点:
for ($i=0; $i<$arrayCart.length; $++ ){ // <----- lol @ $++
但是通过这种方式,我的会话中只有一个对象..?这将只允许购物车中有一个项目。是的,你是对的。我猜代码在你的更改后会工作,但是它不是很有效。Reed但是下面的@Tom down用一个更有用的答案击中了它的头部。此外,如果客户多次添加一个产品,它也会被存储几次购物车中的l次。如果项目id用作数组索引,则不会发生这种情况。(搜索项目也会更有效)因为php什么时候使用了点符号?????你把js和php搞混了。我建议你买一本书,用一个想法。我看到的最明显的一点是使用serialize——这个函数是用来写入文件或数据库的——如果你的数据是原生php,那么就把它作为php保存
for ($i=0; $i<$arrayCart.length; $++ ){ // <----- lol @ $++
function removeitem ($item){
$arrayCart = $_SESSION['cart'] ;
for ($i=0; $i<$arrayCart.length; $++ ){
if ($item.id == $arrayCart[i].id){
$arrayCart.splice (i,0);
}
}
}