2016-07-13 83 views
0

我正在CakePHP 3.2中工作並構建購物車。我使用Cookie組件來將產品存儲在購物車中。CakePHP 3:創建多維餅乾

這是我在做什麼將產品添加到購物車

public function addToCart() 
    { 
     $this->loadModel('Products'); 

     if ($this->request->is('post')) { 
     $p_id = $this->request->data('product_id'); 
     $p_quantity = $this->request->data('qnty'); 

     $product = $this->Products->get($p_id); 

     if (!$product) { 
      throw new NotFoundException(__('Invalid Product')); 
     } 

      $this->Cookie->write('Cart', 
      ['id' => $p_id, 'quantity' => $p_quantity]); 

      $itemsCount = count($this->Cookie->read('Cart')); 

      $this->Flash->success(__('Product added to cart')); 
      return $this->redirect($this->referer()); 

     } 
    } 

我怎麼能在Cookie添加多維數組,因爲車可以有多個產品,每個產品攜帶多個值。 另外,如何在cart()view中打印?

這是我cart()方法是如何

public function cart() 
    { 
     $cart_products = $this->Cookie->read('Cart'); 

     $this->set('cart_products', $cart_products); 
    } 

,並打印在視圖

foreach($cart_products as $c_product): 
    echo $c_product->id.' : '.$c_product->quantity; // line 45 
endforeach; 

但是這給了錯誤的

Trying to get property of non-object [ROOT/plugins/ArgoSystems02/src/Template/Orders/cart.ctp, line 45] 
+1

使用echo $ c_product [ '身份證']「。 :'。$ c_product ['quantity'];在線45 –

+0

這是正確的打印一個單一的cookie值。我想在cookie中存儲一個數組並循環遍歷它以打印所有'id'和'quantity'。此代碼需要刪除'foreach()'循環,並使用'$ cart_products ['id']打印' –

+0

請檢查我的答案,並讓我知道謝謝:-) –

回答

1

你寫數組餅乾:

$this->Cookie->write('Cart', ['id' => $p_id, 'quantity' => $p_quantity]); 

我相信你想要的是存儲所有產品的cookie:

$cart = $this->Cookie->read('Cart') ? $this->Cookie->read('Cart') : []; 
$cart[] = $product; 
$this->Cookie->write('Cart', $cart) 
+0

從第一行開始,每次添加新產品時,先前寫入的項目的數據將被新的數據替換。我想添加所有產品而不更換一個。 –

+0

它讀取已添加的產品,或者如果cookie不存在,則創建新的數組。 –

+0

如何更新這個cookie中的特定數組值 –

1

請嘗試以下

代替方法

$this->Cookie->write('Cart',['id' => $p_id, 'quantity' => $p_quantity]); 

進入

$cart = []; 
if($this->Cookie->check('Cart')){ 
    $cart = $this->Cookie->read('Cart'); 
} 
$cart[] = ['id' => $p_id, 'quantity' => $p_quantity];//multiple 
$this->Cookie->write('Cart', $cart); 

相反視圖

foreach($cart_products as $c_product): 
    echo $c_product->id.' : '.$c_product->quantity; // line 45 
endforeach; 

進入

foreach($cart_products as $c_product): 
    echo $c_product['id'].' : '.$c_product['quantity']; // line 45 
endforeach;