简体   繁体   中英

php array cart problem?

I have the following code:

if($_SESSION['basket']){
    $i=0;
    while($i < count($_SESSION['basket'])) {    
        if(is_array($_SESSION['basket'][$i][$product['productid']]) && $_SESSION['basket'][$i][$product['productid']]['material']==$_POST['material'] && $_SESSION['basket'][$i][$product['productid']]['size']==$_POST['size']){
            $_SESSION['basket'][$i][$product['productid']]['qty']+=$_POST['qty'];
        }else{
            echo $i."-4";
            $_SESSION['basket'][][$product['productid']] = array("qty"=>$_POST['qty'], "material"=>$_POST['material'],"size"=>$_POST['size']);
        }
        $i++;
    }   
}else{
    $_SESSION['basket'][][$product['productid']] = array("qty"=>$_POST['qty'], "material"=>$_POST['material'],"size"=>$_POST['size']);
}

and when I add an item to the basket the qty displayed for a product is 2 when I am only adding 1 also sometimes extra products are also sometime added can anyone help me?

I would double check that $_SESSION['basket'][$i][$product['productid']]['qty'] plus $_POST['qty'] equals your desired value for starters, echo it out, make sure they're ints (if you haven't already)

And try

$_SESSION['basket'][$i][$product['productid']]['qty'] = $_SESSION['basket'][$i][$product['productid']]['qty'] + $_POST['qty'];

instead of using the += operator. It's given me problems in the past.

Or your count($_SESSION['basket']) may be equaling 2 , therefor running the addition twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM