calculating array data
I have the fol开发者_JAVA百科lowing in my db.
Orders: id: 1 id: 2 id: 3
Order_Items id: 1, order_id: 1, cost: 10 id: 2, order_id: 1, cost: 15 id: 3, order_id: 2, cost: 5 id: 4, order_id: 2, cost: 60
I then have the following code to output each order and it's total cost:
$total = 0;
foreach($orders as $order)
{
foreach($order->getOrderItems() as $o)
{
$total += $o->getCost();
}
$content_file .= $total_price . "\r\n";
}
echo $content_file;
All works fine, a part from it get the first total 25
, then for the next order, gets the first total and adds it to the 2nd(90) and so on.
Is there anyway I can change my logic to output each order row and the total cost, rather than the addition that is currently going on?
Thanks
You need to move the $total = 0 line as follows :
foreach($orders as $order)
{
$total = 0;
foreach($order->getOrderItems() as $o)
{
$total += $o->getCost();
}
$content_file .= $total . "\r\n";
}
echo $content_file;
精彩评论