2014-03-28 125 views
0

基本上我一直在向Shop類寫一個UpdateCart函數。這個想法是Cart是一個會話數組,一個項目被添加爲一個像array(1 => array(), 2 = array()等數組中的新數字。PHP更新購物車陣列

public function updateCart($ID, $Proc) { 
    switch($Proc) { 
     case $Proc = "Add" : 
      try { 
       $item = $this->_db->get("Shop","WHERE $ID = id"); 
       $this->cartArray[ count($this->cartArray) + 1 ] = array (
        "ID" => $item['id'], 
        "Name" => $item['name'], 
        "Desc" => $item['desc'], 
        "Price" => $item['price'] 
       ); 
       session::put('ShoppingCart', $this->cartArray); 
       print_r($_SESSION['ShoppingCart']); 
      } catch(Exception $e) { 
       die("No Item with That ID Found"); 
      } 
      break; 
     case $Proc = "Remove" : 
      echo "Item ".$item['ID']." Removed"; 

      break; 
     default: 
      echo "Nothing to do"; 
      break; 
    } 
} 

唯一的問題是它不能添加到陣列,它只是完全取代,而且我絞盡腦汁找出原因。

回答

0

您每次調用put時都會覆蓋數組,請嘗試push。

public function updateCart($ID, $Proc) { 

    switch($Proc) { 
     case $Proc = "Add" : 
      try { 
       $item = $this->_db->get("Shop","WHERE $ID = id"); 
        $this->cartArray[] = array (
               "ID" => $item['id'], 
               "Name" => $item['name'], 
               "Desc" => $item['desc'], 
               "Price" => $item['price'] 
               ); 
        session::push('ShoppingCart', $this->cartArray); 
        print_r($_SESSION['ShoppingCart']); 
      } catch(Exception $e) { 
       die("No Item with That ID Found"); 
      } 
     break; 
     case $Proc = "Remove" : 
      echo "Item ".$item['ID']." Removed"; 
     break; 
     default: 
      echo "Nothing to do"; 
    } 
} 

如果這也不起作用,嘗試合併它,當你使用put

public function updateCart($ID, $Proc) { 

    switch($Proc) { 
     case $Proc = "Add" : 
      try { 
       $item = $this->_db->get("Shop","WHERE $ID = id"); 
        $this->cartArray[] = array (
               "ID" => $item['id'], 
               "Name" => $item['name'], 
               "Desc" => $item['desc'], 
               "Price" => $item['price'] 
               ); 
        session::put('ShoppingCart', array_merge(session::get('ShoppingCart'), $this->cartArray)); 
        print_r($_SESSION['ShoppingCart']); 
      } catch(Exception $e) { 
       die("No Item with That ID Found"); 
      } 
     break; 
     case $Proc = "Remove" : 
      echo "Item ".$item['ID']." Removed"; 
     break; 
     default: 
      echo "Nothing to do"; 
    } 
} 
+0

我用第二種方法,它完美的作品謝謝! – BionicBear