2016-07-13 108 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;