在symfony2中为shoppingg购物车更新会话

时间:2015-06-16 09:42:26

标签: php symfony symfony-2.1 php-5.3 symfony-2.3

我有以下代码:

public function addAction(Request $request){
    //Get submited data
    // Get Value from session
    $sessionVal = $this->get('session')->get('aBasket');
    // Append value to retrieved array.
    $aBasket = $request->request->all();
    if(count($sessionVal) > 0) {
        foreach ($sessionVal as $key=>$value) {
            if($aBasket['product_id'] == $sessionVal[$key]['product_id'])
            {
                $sessionVal[$key]['product_quantity'] = $sessionVal[$key]['product_quantity'] + $aBasket['product_quantity'];
                $this->get('session')->set('aBasket', $sessionVal);
            }
            else
            {
                $sessionVal[] = $aBasket;
                $this->get('session')->set('aBasket', $sessionVal);
            }
        }
    }
    else
    {
        $sessionVal[] = $aBasket;
        $this->get('session')->set('aBasket', $sessionVal);
    }
    // Set value back to session
    return $this->redirect($this->generateUrl('shop_desktop_homepage'));
}

想法是增加现有产品的数量,如果id未对应,则添加它们。现在数量正确添加,但产品也被添加。现有解决方案?请帮帮我......

1 个答案:

答案 0 :(得分:1)

您可以简化代码,我猜您的会话数组看起来像

array(
    '11' =>array('id'=>'11','title'=>'some product','product_quantity'=>2),
    '12' =>array('id'=>'12','title'=>'some product','product_quantity'=>1),
    '13' =>array('id'=>'13','title'=>'some product','product_quantity'=>3),
);
您的购物车数组中的

键将是产品ID,因此现在在下面的代码中不会有重复的产品数据我已经删除了foreach循环而我只使用了if if if(isset($sessionVal[$aBasket['product_id']]))是否产品ID已经存在于购物车数组中,只需将产品ID代替密钥,例如if(isset($sessionVal['11']))如果存在,则将数量增加1,如果不存在则将产品插入购物车数组

public function addAction( Request $request ) {
    $sessionVal = $this->get( 'session' )->get( 'aBasket' );
    $aBasket = $request->request->all();
    if(isset($sessionVal[$aBasket['product_id']])){
        $sessionVal[$aBasket['product_id']]['product_quantity'] += 1;
    }else{
        $sessionVal[$aBasket['product_id']]= array(
            'id'=>$aBasket['product_id'],
            'product_quantity' => 1,
            'other_info' => '...'
        );
    }
    $this->get( 'session' )->set( 'aBasket', $sessionVal );
    return $this->redirect( $this->generateUrl( 'shop_desktop_homepage' ) );
}