2014-12-03 63 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++; 
} 

}