2016-11-16 70 views
1

我正在开发一个php购物车,并试图让购物车更新该项目的数量,而不是为同一项目创建新条目。但是,当输入已经在购物车中的产品时,我的foreach语句仅针对第一个数组值对其进行检查,然后为该产品创建一个新条目。foreach只检查数组中的第一个值,然后创建新值

有人可以帮助我通过这个工作,并找出为什么它不检查整个数组列表?

这里是我的更新方法:

function CheckForExistingEntry($id, $setOf, $quantity) { 
// if the product ID and the SET OF is equal in multiple products, update the quanity instead of making new records 
foreach ($_SESSION['shopping_cart'] as $key => $product) { 
    if ($id == $product['product_id'] && $setOf == $product['setOf']) { 
     // Update Cart Value 
     $_SESSION['shopping_cart'][$key]['quantity'] += $quantity; 
     $_SESSION['shopping_cart'][$key]['price'] *= $_SESSION['shopping_cart'][$key]['quantity']; 
     break; 
    } else { 
     // Add New Cart Value 
     AddToCart($id, $setOf, $quantity); 
     break; 
    } 
} 
} 

回答

1

您在这两个ifelsebreak;,这意味着它会在第一次迭代后总是打破。

让我们删除else -block,因为我们只是想继续下一个项目,如果它没有找到。

试试这个:(我评论的变化):

// Define a variable that holds the state. 
$updated = false; 

foreach ($_SESSION['shopping_cart'] as $key => $product) { 
    if ($id == $product['product_id'] && $setOf == $product['setOf']) { 
     // Update Cart Value 
     $_SESSION['shopping_cart'][$key]['quantity'] += $quantity; 
     $_SESSION['shopping_cart'][$key]['price'] *= $_SESSION['shopping_cart'][$key]['quantity']; 

     // Set updated as true and break the loop 
     $updated = true; 
     break; 
    } 
} 

if (!$updated) { 
    // We didn't update any items, add a new item instead 
    AddToCart($id, $setOf, $quantity);  
} 
相关问题