带键和if语句的foreach循环结构

时间:2017-05-23 14:28:52

标签: php oop foreach

我在这里做错了什么?我想我已经看了太长时间,因为我无法发现它。

我正在尝试运行一个循环,基本上说,如果购物车是空的,添加产品,如果购物车不是空的,检查产品是否存在。如果是,请增加数量,如果它没有将其作为新产品添加到购物车中。

public function addProductToCart($product_id){
  if(!empty($_SESSION['cart_products'])){
    foreach($_SESSION['cart_products'] as $i => $item) {
      if($_SESSION['cart_products'][$i]['id'] == $product_id){
        $_SESSION['cart_products'][$i]['quantity'] += 1;
      }
      if($_SESSION['cart_products'][$i]['id'] != $product_id){
        $newProduct = array("id" => $product_id, "quantity" => 1);
        array_push($_SESSION['cart_products'],$newProduct);
      }
    }
  } else {
    $newProduct = array("id" => $product_id, "quantity" => 1);
    array_push($_SESSION['cart_products'],$newProduct);
  }
}

点击几个产品几次以测试它是否有效,我的数组看起来像这样

array(1) {
 ["cart_products"]=>
  array(6) {
    [0]=>
     array(2) {
       ["id"]=>
       string(1) "1"
       ["quantity"]=>
       int(5)
       }
      [1]=>
      array(2) {
       ["id"]=>
       string(1) "2"
       ["quantity"]=>
       int(1)
    }
     [2]=>
     array(2) {
     ["id"]=>
     string(1) "3"
     ["quantity"]=>
     int(2)
    }
    [3]=>
    array(2) {
      ["id"]=>
      string(1) "3"
      ["quantity"]=>
      int(2)
    }
    [4]=>
    array(2) {
      ["id"]=>
      string(1) "3"
      ["quantity"]=>
      int(1)
    }
    [5]=>
    array(2) {
      ["id"]=>
      string(1) "3"
      ["quantity"]=>
      int(1)
    }
  }
}

传入的$product_id参数只是一个整数。

2 个答案:

答案 0 :(得分:2)

更改if内的代码 - 阻止:

// special flag
$product_found = false;
foreach($_SESSION['cart_products'] as $i => $item) {
  // here you found the required ID
  if($_SESSION['cart_products'][$i]['id'] == $product_id){
    $_SESSION['cart_products'][$i]['quantity'] += 1;
    // set flag as found
    $product_found = true;
    // break loop as you already found and incremented a required value
    break;
  }
}

// if you didn't find required value - add a new one
if (!$product_found) {
  $newProduct = array("id" => $product_id, "quantity" => 1);
  array_push($_SESSION['cart_products'],$newProduct);
}

答案 1 :(得分:0)

您的每个产品都有一个唯一的ID(或者至少,我希望他们有)。因此,您应该利用这些ID,将这些ID用作购物车中的钥匙。

public function addProductToCart($product_id)
{
    $products = $_SESSION['cart_products'];

    if (array_key_exists($product_id, $product) === false) {
        $products[$product_id] = 0;
    }

    $products[$product_id] += 1;

    $_SESSION['cart_products'] = $products;
}

这样,会话中的cart_products值将包含productID => quantity对。

注意:

"错误"部分实际上是那里的大部分代码。

您的购物车实体不应直接与持久性(在本例中为会话)进行交互。 写入持久性应该可以通过单独的类(data mapper)完成,因为这样你至少可以添加一些单元测试。