2017-07-31 167 views
-2

我在购物车会话(数组)中添加了一些项目,但我想删除1行,因为我写了下面的代码,但那不适用于我。如何从多维数组中删除行cakephp

public function deletecart() { 
$this->loadModel("Product"); 
    if($this->Session->check('cart') AND count($this->Session->read('cart'))>0) 
    { 
     foreach ($this->Session->read('cart') as $key => $value) { 
     if ($value['0']['Product']['id'] == "12") { 
     unset($this->Session->read('cart')[$key]); 
     } 
     } 
    } 
} 

这里是我的会话调试值

array(
    '[0]' => array(
     (int) 0 => array(
      'Product' => array(
       'id' => '8', 
       'category' => 'Pendant', 
      ) 
     ) 
    ), 
    (int) 1 => array(
     (int) 0 => array(
      'Product' => array(
       'id' => '12', 
       'category' => 'Pendant' 
      ) 
     ) 
    ) 
) 

回答

1

你不能像这样取消设置会话密钥值。您将不得不将Session密钥值存储在临时变量中。

$sessionArr = $this->Session->read('cart'); 
foreach ($sessionArr as $key => $value) { 
    if ($value['0']['Product']['id'] == "12") { 
// Unset key 
     unset($sessionArr[$key]); 
    } 
} 

// Assign $sessionArr value to cart key 
$this->Session->write('cart',$sessionArr); 
+0

这也是行不通的。 – prameshwer

+0

@prameshwer。我已经在我的电脑中测试过它,它正在工作。分享你的代码。 –

+1

我很抱歉它真的工作感谢的人:) – prameshwer