2016-04-14 19 views
1

我知道這是一個轉儲/基本問題,但我卡住了,可以使用一些幫助成爲一個新手。調試foreach

我試圖實現的目標:我想要一個foreach循環來獲取用戶購物車中的所有產品名稱。

問題: foreach循環在第二次迭代後停止(如果購物車中有三件東西,而且我轉儲,則只顯示2(第一和第二))。

我知道什麼是foreach循環。我認爲我的問題存在於我的變量名中,但我試圖與他們混在一起無濟於事。

if (is_null($cart) || $cart->getSubmitted(true)) { 
    $cart = new UserCart(); 
    // since new cart no need to check for duplicate product quantity 
    // add product to cart 
     $this->addFlash('notice', 'Creating a new cart because one didnt exist for the user before.'); 
} 
else { 

    $quantity = new Quantity(); 

    //If the cart is set 

    $getProductsInCurrentUsersCart = $cart->getQuantities(); //All Products In Users Cart (ARRAY COLLECTION/PERSITENT COLLECTION) 

    foreach ($getProductsInCurrentUsersCart as $key => $value) { 

     dump($getProductsInCurrentUsersCart); 
     $getProductsInCurrentUsersCart = $value->getProduct()->getName(); //SHOULD BE ALL PRODUCTS IN CART 

     if ($getProductsInCurrentUsersCart === $quantity->setProduct($productBeingAddedToCart)->getProduct()->getName()) { 
      $this->addFlash('notice', 'Comparission was TRUE.'); 
      $quantity->setQuantity($quantity->getQuantity() + 1); 
     } 
     else { 
      $quantity->setQuantity(1); 
      $quantity->setProduct($productBeingAddedToCart); 
      $this->addFlash('notice', 'Comparisson was FALSE.'); 
     } //ENDS IF/ELSE 

    } //EXECUTING ONCE?????????? 


    $cart->setTimestamp(new \DateTime()); // Set Time Product was Added 
    // $quantity->setQuantity(1); // Set Quantity Purchased 
    $cart->setSubmitted(false); // Set Submitted 
    $cart->setUser($this->getUser()); // Sets the User ONCE 
    $cart->addQuantity($quantity); // Add Quantity ONCE 
    $quantity->setUserCart($cart); // Create a UserCart ONCE     
    $em->persist($productBeingAddedToCart); 
    $em->persist($cart); 
    $em->persist($quantity); 
    $em->flush(); 
    $this->addFlash('notice', 'The product: '.$productBeingAddedToCart->getName().' has been added to the cart!'); 
} 

任何幫助真的很感激!

+0

爲什麼你要在循環內重新定義'$ getProductsInCurrentUsersCart'列表?我認爲這可能是問題... – fonfonx

回答

1
$getProductsInCurrentUsersCart = $value->getProduct()->getName(); 

這裏您正在重新定義循環內的列表變量。嘗試使用$ getProductsInCurrentUsersCart2並將其更改爲在該行下面。看看是否解決它。然後拿出一個更好的名字:)