如何在php中使用session增加项目数量

时间:2014-05-13 07:34:18

标签: php arrays session

$product_code = $_POST['cart_id'];
$temp_quantity = $_POST['quantity'];
$price = $_POST['price'];

foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
{                        
    if($cart_itm["id"] == $product_code){ //the item exist in array

        $product[] = array('name'=>$cart_itm["name"], 
                           'id'=>$cart_itm["id"], 
                           'qty'=>$temp_quantity, 
                           'price'=>$cart_itm["price"]);
        $found = true;

    }else{

        //item doesn't exist in the list, just retrive old info and prepare array for session var

        $product[] = array('name'=>$cart_itm["name"], 'id'=>$cart_itm["id"], 'qty'=>$temp_quantity, 'price'=>$cart_itm["price"]);

    }

    $_SESSION["products"] = $product;

}

此代码完全适用于单个产品以增加其数量,但是当需要在购物车中的许多产品中增加一个产品数量时,它会增加整个产品数量。它会创建一个新会话,那么如何通过更正相同的代码来增加代码中的许多产品中的任何一个?

1 个答案:

答案 0 :(得分:0)

如果您遇到会话问题,请在开始时调用session_start()...

Session_start

(检查会话是否先存在)

但我猜问题就在这里......

$_SESSION['products'] = $product;

一直覆盖会话变量!所以,即使你有100种产品,你也会得到最后一种产品

试试这个

foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
{                        
    if($cart_itm["id"] == $product_code){ //the item exist in array

        $product[] = array('name'=>$cart_itm["name"], 
                           'id'=>$cart_itm["id"], 
                           'qty'=>$temp_quantity, 
                           'price'=>$cart_itm["price"]);
        $found = true;

    }else{

        //item doesn't exist in the list, 
        //just retrive old info and prepare array for session var

        $product[] = array('name'=>$cart_itm["name"], 
                           'id'=>$cart_itm["id"], 
                           'qty'=>$temp_quantity, 
                           'price'=>$cart_itm["price"]);

    }

    $products[] = $product;             //<-- Changed (tempArray)

}

$_SESSION["products"] = $products;      //<-- Temp to session