简体   繁体   English

PHP将GET var附加到SESSION

[英]PHP appending GET vars to SESSION

I wanted to make a simple shopping cart which takes a $_GET variable and puts it in the $_SESSION variable. 我想制作一个简单的购物车,它将$ _GET变量放入$ _SESSION变量。 The code I have tried is this: 我尝试过的代码是这样的:

<?php 
    session_start();
    if (is_numeric($_GET['add'])) $_SESSION[(string)$_GET['add']] = 1; ?>

Because my item ids are numeric so I check first to stop random things to be added to the session variable. 因为我的商品ID是数字的,所以我首先检查停止将随机的东西添加到会话变量中。 I then then do a var_dump to see the result. 然后,我执行var_dump以查看结果。 The first time I run the code with ?add=102 I get: 第一次使用?add = 102运行代码时,我得到:

array(1) { [102]=> int(1) }

I then run the script again with ?add=108 I get: 然后,我再次使用?add = 108运行脚本:

array(1) { [108]=> int(1) }

What I want is: 我想要的是:

array(2) { ["102"]=> int(1), ["108"]=> int(1) }

What am I doing wrong? 我究竟做错了什么? My concept is to convert the $_GET variable to a string and store the quantity 1 and the string value of $_GET in $_SESSION associatively. 我的概念是将$ _GET变量转换为字符串,并将数量1和$ _GET的字符串值关联存储在$ _SESSION中。 This should allow me to add as many items as long as their id is not the same, which is what I want. 只要我的ID不相同,这应该允许我添加尽可能多的项目。

Here is alternatives I have tried: 这是我尝试过的替代方法:

strval($_GET['add']), 
(string)($_GET['add']), 
$_GET['add']

Nothing seems to work. 似乎没有任何作用。

Any help would be appreciated. 任何帮助,将不胜感激。

You cannot use $_SESSION keys that are numeric. 您不能使用数字的$_SESSION键。 Create another array in the session, eg $_SESSION['items'] 在会话中创建另一个数组,例如$_SESSION['items']

Then: 然后:

session_start();
if(is_numeric($_GET['add']))
{
    $_SESSION['items'][(string)$_GET['add']] = 1;
}

It's much easier to iterate over this items array later, when you have other information in your session. 当会话中有其他信息时,稍后遍历此items数组要容易得多。

I realise this is an amalgamation of Satya's comment and mthie's answer but the complete answer should I think be 我意识到这是Satya的评论和mthie的回答的结合体,但完整的答案应该是

  1. You would be well advised to encapsulate the array you are building in its own named location and 建议您将要构建的阵列封装在其自己的命名位置,然后
  2. you need to add to the array each time rather than overwrite it 您需要每次add to数组而不是overwrite

so try 所以尝试

<?php
    session_start();
    if(is_numeric($_GET['add'])) {
       $_SESSION['add'][][(string)$_GET['add']] = 1;
    }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM