user2762858
user2762858

Reputation: 11

Foreach within a while loop

I'm having an issue with a foreach loop iterating its entire array contents in each instance of the while loop.

I've tried moving the loop, adding break & continue points and using alternate syntaxes-- I feel like I'm just missing something small here. Do I need to further define the array? Do I integrate the foreach loop into the while somehow? Any pointers would be much appreciated. Here is a basic run down of the code (using "Shopp" an ecommerce plugin with a similar code example at: https://shopplugin.net/api/shopp_cart_items/):

<?php  while(shopp('cart','items')): // initializes the shopping cart loop

           $Items = shopp_cart_items(); 
            foreach ( $Items as $item ):

        echo $item->quantity * $item->weight; // multiplies weight by quantity

                endforeach; echo 'g'; endwhile; ?>

The products are measured in weight, so as an example, there are 2 items in the cart with their weights at 1 gram, and 2 grams respectively.

Here's the current output:

Cart item 1 - Weight: 12g
Cart item 2 - Weight: 12g

Here's the expected output:

Cart item 1 - Weight: 1g
Cart item 2 - Weight: 2g

Thanks in advance!

IH

Edit:

There is no documentation in Shopp concerning product weight, so I had to find the product object and arrays and added an ++ operator to cycle through them with each while iteration. Here is the code I used.

echo $Items[$i++]->option->dimensions['weight'] * shopp('cartitem','quantity', 'echo=false');

with the integer set outside the loop: $i = 0;

Upvotes: 1

Views: 303

Answers (2)

RST
RST

Reputation: 3925

another approach

  $product_id = shopp('cartitem.get-product');
  $weight = shopp('product.get-weight'); // use product tag to get weight
  $quantity = shopp('cartitem.get-quantity'); // use cart-item tag to get quantity
  echo $weight * $quantity .' g';

Upvotes: 0

Chris Pierce
Chris Pierce

Reputation: 736

echo $item->quantity * $item->weight; // multiplies weight by quantity

is probably returning improperly, but could be as simple as

echo ($item->quantity * $item->weight);

I'd also recommend using something besides Item as $item $Item and $items is getting really confusing to look at.

Upvotes: 0

Related Questions