Display results using foreach loop and sessions in Symfony for PHP

I’m writing a shopping cart page for shoes shop website using sessions in Symfony for PHP. It enables to add an item of selected size to cart and count a quantity. I need to know how to display the cart using foreach loop.

Here’s a function of adding a product:

public function add($shoesid, $sizeid, SessionInterface $session)
{
    $cart = $session->get('cart', []);
    if(!empty($cart[$shoesid][$sizeid])) {
        $cart[$shoesid][$sizeid]++;
    } else {
        $cart[$shoesid][$sizeid] = 1;
    }
    $session->set('cart', $cart);
    dd($session->get('cart'));
}

Here’s a message what I get when I add an item:

> array:2 [▼   
40024 => array:1 [▼   
410 => 2     
]   
]

(where 40024 is shoesid, 410 is sizeid and 2 is quantity (count of [shoesid][sizeid])

And here’s a function to display a shopping cart

public function index(SessionInterface $session, ShoesRepository $shoesRepository, CountriesRepository $countriesRepository, StockRepository $stockRepository)
{
    $cart = $session->get('cart', []);
    $cartWithData = [];
    foreach($cart as $shoesid => [$sizeid => $quantity]) //error here
    {
        $cartWithData[] = [
            'shoe' => $shoesRepository->shoeDescr($shoesid),
            'shoePrice' => $shoesRepository->find($shoesid),
            'quantity' => $quantity,
            'size' => $stockRepository->shoeSizeCart($shoesid, $sizeid)
        ];
    }        
    $total=0;
    $delivery=20;

    foreach($cartWithData as $item) 
    {
        $totalItem = $item['shoePrice']->getShoesPrice()*$item['quantity'];
        $total += $totalItem;            
    }
    $countries = $countriesRepository->findBy(array(), array('countryname' => 'asc'));
    dd($cartWithData);
}

But when I try to launch a cart page I get the next error (in line 9):

Notice: Undefined variable: sizeid

What code changes should I make to display items correctly

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *