2014-12-03 54 views
1

我查看过,并且无法找到如何更改会话变量并将其存储回数组。我的代码做到目前为止我所需要的,并将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']; 
} 

任何帮助,即使它的指向我在文章中,我没能看会有所帮助。

此外,代码风格的任何指针将不胜感激。

+0

了''在$ _SESSION'阵列的print_r',你想它改变了什么而改变它的标准将有所帮助。 – AbraCadaver 2014-12-04 00:00:18

+0

为什么2 $ foreach'$ _SESSION ['products']'? '$ a'与'$ cart_itm'不一样吗? – 2014-12-04 00:02:07

+0

@abracadaver所以要改变它会是print_r($ cart_itm [$ number] ['qty'])? – helmet648 2014-12-04 00:15:11

回答

1

这大概应该做的:

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

如果没有,使用相同的理念:你有key它允许您指定要更改的数组中的项目。

+0

谢谢你!这连同对我的问题的评论帮助我设置了变量 – helmet648 2014-12-04 00:30:36

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++; 
    } 
} 
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++; 
} 

}