0

I wanted to make a simple shopping cart which takes a $_GET variable and puts it in the $_SESSION variable. 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. I then then do a var_dump to see the result. The first time I run the code with ?add=102 I get:

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

I then run the script again with ?add=108 I get:

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. This should allow me to add as many items as long as their id is not the same, which is what I want.

Here is alternatives I have tried:

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

Nothing seems to work.

Any help would be appreciated.

4

2 回答 2

3

您不能使用$_SESSION数字键。在会话中创建另一个数组,例如$_SESSION['items']

然后:

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

当您的会话中有其他信息时,稍后迭代此 items 数组会容易得多。

于 2013-08-14T09:03:57.513 回答
0

我意识到这是 Satya 的评论和 mthie 的回答的结合,但我认为完整的答案应该是

  1. 建议您将正在构建的数组封装在其自己的命名位置,并且
  2. add to你每次都需要数组而不是overwrite

所以试试

<?php
    session_start();
    if(is_numeric($_GET['add'])) {
       $_SESSION['add'][][(string)$_GET['add']] = 1;
    }
?>
于 2013-08-14T09:18:25.430 回答