PHP Sessions shopping cart: update product if it's already id the session

后端 未结 4 1445
北海茫月
北海茫月 2021-01-26 09:22

I have struggled to find a solution to a simple shopping cart with $_SESSION. I kept it very simple and this is my code right now

if ( Input::isPos         


        
4条回答
  •  孤独总比滥情好
    2021-01-26 09:43

    The problem is here :

    if ( $_SESSION['cart'][$id][0] == $size ) {
        $_SESSION['cart'][$id][1]+=$qta;
    } else {
        $_SESSION['cart'][$id] = array( $size, $qta );
    }
    

    If the size is different, you replace it by a new array (the else of the bloc). That's your array :

    Array(
        'cart'=>array(
            'id'=>array('size', 'qta')
        )
    )
    

    With that structure, you can have only one size for an id, so if you want to add another instead of replace the old one, you should consider working with that :

    Array(
        'cart'=>array(
            'id'=>array(0=>array('size1'=>'qta1'), 1=>array('size2'=>'qta2'))
        )
    )
    

    Of course, this means you will need to loop over the array to find the right size and, then, update the qta. Not fun.

    This structure may be more interesting to work with :

    Array(
        'cart'=>array(
            'id'=>array('size1'=>'qta1', 'size2'=>'qta2')
        )
    )
    

    So, instead of checking $_SESSION['cart'][$id][0] == $size, you just need to check if $_SESSION['cart'][$id][$size] exists (with an array_key_exists) and go on :)

提交回复
热议问题