【问题标题】:foreach only checks first value in array, then creates new valueforeach 只检查数组中的第一个值,然后创建新值
【发布时间】:2017-03-31 04:22:05
【问题描述】:

我正在开发一个 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;
    }
}
}

【问题讨论】:

    标签: php html css


    【解决方案1】:

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

    让我们删除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);    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多