添加到购物车功能创建错误的数组

时间:2014-04-27 21:56:21

标签: php arrays session shopping-cart

我尝试将产品添加到购物车,但我对循环逻辑有一些问题。 此功能应添加新产品并检查产品ID是否已在购物车中。如果它在购物车中,则应将现有产品或用户选择的数量加1。 这是我的一些代码:

function AddToCart($pid, $q)
{
$quantity = $q;
$product_id = $pid;
if (is_array($_SESSION['products']))
    {
    foreach($_SESSION['products'] as $key => $my_value)
        {
        if ($pid === $my_value['product_id'])
            {
            if ($quantity != 1)
                {
                $quantity = $my_value['quantity'] + $quantity;
                $_SESSION['products'][$key]['quantity'] = $quantity;
                }
              else
                {
                $quantity = $my_value['quantity'] + 1;
                $_SESSION['products'][$key]['quantity'] = $quantity;
                }
            }
          else
            {
            $_SESSION['products'][] = array(
                'product_id' => $product_id,
                'quantity' => $quantity,
            );
            }
        }
    }
  else
    {
    $_SESSION['products'][] = array(
        'product_id' => $product_id,
        'quantity' => $quantity,
    );
    }
}

$ _SESSION的var_dump将如下:

   array(8) { 
   [0]=> array(2) { ["product_id"]=> int(4) ["quantity"]=> int(1) } 
   [1]=> array(2) { ["product_id"]=> int(10) ["quantity"]=> int(1) } 
   [2]=> array(2) { ["product_id"]=> int(11) ["quantity"]=> int(2) } 
   [3]=> array(2) { ["product_id"]=> int(11) ["quantity"]=> int(3) } 
   [4]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(2) } 
   [5]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(3) } 
   [6]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(4) } 
   [7]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(5) } } 

虽然我只添加了4种产品:id 4,10,11和12

1 个答案:

答案 0 :(得分:0)

function AddToCart($pid, $q){  
    if(!is_array($_SESSION['products'])){
        $_SESSION['products'] = array();
    }
    foreach($_SESSION['products'] as $key=>$my_value){
        if($pid === $my_value['product_id']){
            $_SESSION['products'][$key]['quantity'] += $q;
            return true;
        }   
    }
    $_SESSION['products'][] = array('product_id' => $pid,
                                    'quantity' => $q);
    return true;
}