Dominykas55
Dominykas55

Reputation: 1231

Nesting arrays and foreach loops

I need to make a function somehow that gets a value from one array, then the other and combines them.

This is what I mean:

I have an array called products with all of the products information(name, price, etc..) and an array called cart, that has a specific products Id and its quantity.

Now I want to count the total price of the cart and that means I need to somehow access both foreach loops(I need to get the price from the array loop and increment it with the quantity of the cart loop).. This is what I tried so far:

public function getTotalCart($items, $cart)
{
    $total = 0;  // the final price(with discount, tax and etc) of a single product(without quantity)
    $qtyTotal = 0;  /// the final price with the quantity

    foreach ($items as $item) {
        $total = $item->getFinal();  // I am getting the final price of the item

        foreach ($cart as $id=>$quantity) {      
            $qtyTotal += $quantity * $total;  // I am incrementing the quantity of the product with the products final price.
        }
    }

    return $qtyTotal;
} 

This works when I have one product, but if I add another one the pricing is wrong.. Any ideas?

Upvotes: 0

Views: 66

Answers (3)

Plamen Ivanov
Plamen Ivanov

Reputation: 101

I think the second foreach is breaking it. With the first foreach you are looping the items and if it is correct what you said , that cart has the same items it will execute the cart loop for each item you have. So if you have 4 items, you will go once trough the first foreach but you will go 16 times trough the second one. Maybe you can do something like

foreach($items as $item){
    $total = $item->getFinal();
    $qtyTotal += $cart[$item->id] * $total;
}

Upvotes: 0

Furgas
Furgas

Reputation: 2844

You have to check if the $id in cart is the same as $item id.

...
foreach($cart as $id=>$quantity) {
    if ($id == $item->getId()) {
        $qtyTotal += $quantity * $total;
    }
}
...

Better off, make $items array id-indexed and then only iterate over cart:

public function getTotalCart($items, $cart)
    $qtyTotal = 0;
    foreach($cart as $id => $quantity) {
        $qtyTotal += $quantity * $items[$id]->getFinal();
    }
    return $qtyTotal;
}

Upvotes: 0

RSez
RSez

Reputation: 271

If $cart is an array where the key corresponds to the item id and the value to the quantity, you can do:

foreach ($items as $item) {
    if (array_key_exists($item->getId(), $cart)) {
        $qtyTotal += $cart[$item->getId()] * $item->getFinal();
    }
}

Upvotes: 1

Related Questions