0

It seems very basic, but I stuck on this one.

$value = 0;
foreach($this->products->result() as $this->product)
{
    $value += $this->product->price;
}
//$value += $this->get_order_shipping_cost($orders_id);

return $value;

The value supposed to get added to create total price and then outside the loop to add a shipping cost, but for some reason my loop is returning only the first value, so I am overwriting something somewhere.

2
  • $this->products->result() what is this ? is it an array of products ? Commented Jan 2, 2012 at 12:53
  • are you sure if your loop is running to expected no. of times ? may be its running once only! Commented Jan 2, 2012 at 12:55

2 Answers 2

3

i think this is where the overwrite heapens:

foreach($this->products->result() as $this->product)

i don't know what you're doing before but maybe you could use a temp variable name in the for loop like this:

foreach($this->products->result() as $tempProduct)
{
    $value += $tempProduct->price;
}

hope it works ;) greets, stefan

Sign up to request clarification or add additional context in comments.

Comments

0

You are setting a private member of your class while you only want to get the product and that's it. You don't need to use $this->product, just use a free variable instead, like $product and it should work:

$value = 0;
foreach($this->products->result() as $product)
{
    $value += $product->price;
}

Also if products is one of your objects, you should give it probably a method like getTotalPrice() which just returns the sum, like so:

$value = $this->products->getTotalPrice();

You can then use that more flexible within your code. Hope this is helpful.

1 Comment

Fixed a missing "p" in "product".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.