如何更改会话数组变量的值

时间:2014-12-03 23:56:55

标签: php arrays session

我查看并查看了,并且无法找到如何更改会话变量并将其存储回数组中。我的代码到目前为止做了我想要的,并为变量添加1,但我不知道如何将它保存回数组。我的代码如下。

if(isset($_GET['action']) && $_GET['action'] == 'addp')
{
echo "trying to add 1 item to serial ".$_GET['id']."<br>";
$product_code = filter_var($_GET['id'], FILTER_SANITIZE_STRING);
if(isset($_SESSION['products']))
{
    $number = 0;
    foreach($_SESSION['products'] as $cart_itm)
    {

        if($cart_itm['code'] == $product_code)
        {               
            $a = array($_SESSION['products']);
            foreach($_SESSION['products'] as $a){
                foreach($a as $b){
                    while(list($key, $val) = each($a)){
                        if($key == 'qty'){
                            $val = $val + 1;
                            echo $val;
                        }
                    }
                }
            }               

        }
        else
        {
            echo"Item Code Did not Match";
        }
        $number++;
    }
}
else
{
    echo"Session['Products'] Not Set";
}
}
else
{
    echo"Action is set to ".$_GET['action'];
}

任何帮助,即使它指向我未能看到的帖子也会有所帮助。

此外,任何关于代码风格的指针都将受到赞赏。

3 个答案:

答案 0 :(得分:1)

这可能应该这样做:

if($key == 'qty'){
    $_SESSION['products'][$key] = $val + 1; //this line
    $val = $val + 1;
    echo $val;
}

如果没有,请使用相同的概念:您拥有key,允许您指定要更改的数组中的哪个项目。

答案 1 :(得分:0)

试试这个:

if(isset($_SESSION['products']))
{
    $number = 0;
    foreach($_SESSION['products'] as $cart_itm)
    {
        if($cart_itm['code'] == $product_code)
        {               
            $_SESSION['products']['qty']++; //here is the quantity of the item, no need of more loops
            echo $_SESSION['products']['qty'];
        }
        else
        {
            echo"Item Code Did not Match";
        }
        $number++;
    }
}

答案 2 :(得分:0)

我采取了哪些措施来解决问题

if(isset($_SESSION['products']))
{

$number = 0;

foreach($_SESSION['products'] as $cart_itm)
{
    if($cart_itm['code'] == $product_code)
    {               

        $_SESSION['products'][$number]['qty'] = $cart_itm['qty'] + 1;
    }
    else
    {
        echo"Item Code Did not Match";
    }
    $number++;
}

}