Foreach只检查数组中的第一个值,然后创建新值


foreach only checks first value in array, then creates new value

我正在制作一个php购物车,我试图让购物车更新项目的数量,而不是为同一项目创建新条目。但是,当输入购物车中已经存在的产品时,我的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;
    }
}
}

ifelse中都有一个break;,这意味着它在第一次迭代后总是会中断。

让我们删除else块,因为如果没有找到,我们只想继续下一项。

试试这个:(我已经注释了这些变化):

// 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);    
}
相关文章: