How to sum up number from a foreach?


#1

Hi
I've managed to get this little code working but I need help adding the output.

Here's what I have:

<?php foreach($order->getAllItems() as $item): ?>
<?php if($item->getParentItemId()) continue;?>
<?php $product = Mage::getModel('catalog/product')->load($item->getProductId()); ?>
<?php echo $product->getData('profit'); ?>
<?php endforeach;?>

How can I add the numbers together that this outputs?

Thanks!


#2

Hi @Freejoy, you would perhaps want something similar to this but it is unclear to me whether the values for that property would sum up correctly, you need to make sure first they are the right type or that you parse them correctly before you add them up:

<?php $totalProfit = 0; ?>
<?php foreach($order->getAllItems() as $item): ?>
<?php if($item->getParentItemId()) continue;?>
<?php $product = Mage::getModel('catalog/product')->load($item->getProductId()); ?>
<?php echo $product->getData('profit'); ?>
<?php $totalProfit+=$product->getData('profit'); ?>
<?php endforeach;?>

#3

It doesn't work.

I've been working on it and I got this to work:

<?php foreach($order->getAllItems() as $item): ?>
<?php if($item->getParentItemId()) continue;?>
<?php $product = Mage::getModel('catalog/product')->load($item->getProductId()); ?>
<?php $profit = $product->getData('profit');
<?php $grandprofit += $profit['total']; ?>
<?php endforeach;?>
<?php echo $grandprofit; ?>

But it doesn't work right.

It outputs for 21.97, 23 or 23.00

I can't get it to display the correct decimals.


#4

What is with the endless jumping in and out of Php? You have 100% Php. There should be ONE open tag and ONE closing tag. You are also incorrectly using foreach/endforeach.


#5

Are you trying to get the sum of profit for a Magento sale? If so what is the value of $profit['total'] for each iteration of the loop? If it is a numeric/decimal value you should be able to add them all together.

Also the previous commenter is correct in that this type of logic should not be inside the Magento template but inside a controller or injected into the view some how. Its been about a 2 years since I've used Magento so I can't recall exactly how all that works in the Magento way.


#6

I fixed my code up some:

<?php 
foreach($order->getAllItems() as $item): 
   if($item->getParentItemId()) continue;
$product = Mage::getModel('catalog/product')->load($item->getProductId());
$profit = $product->getData('profit');
$totalprofit += $profit['total'];
endforeach;
?>

I'm not no foreach expert. : ) What's wrong with it?

Also I can understand it a little better writing it that way.


#7

I have to do it the way I can. If i was loaded with money I would hire someone. : )

It's not giving me the correct amounts. Like I said it's spitting out the numbers like 22 instead of 22.95


#8

I think this might help but cannot test right now so a bit unsure:

$totalprofit += (float)$profit['total'];

#9

What you are using is known as an "Alternative Syntax for Control Structures". This is not a situation where you would use it.

You should be using the normal foreach structure.
http://php.net/manual/en/control-structures.foreach.php


#10

I think you need to cast those values to floats or alternatively use the bc math library for mathematical operations on decimal numbers.


#11

Something went wrong ...I can't believe it! : )

I am now back to this:

<?php foreach($order->getAllItems() as $item): ?>
<?php if($item->getParentItemId()) continue;?>
<?php $product = Mage::getModel('catalog/product')->load($item->getProductId()); ?>
<?php echo $product->getData('profit'); ?>
<?php endforeach;?>

But it's outputting the correct values (like 12.9700, 14.8700) but I want to add them together.


#12

@ducatikevin

You mean something like this:

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}

#13

Yes, depending on what you need to do it will be one of these two as the manual shows

foreach (array_expression as $value){
statement
}
foreach (array_expression as $key => $value){
statement
}


#14

This might do it.

<?php 
$totalProfit = 0;
foreach($order->getAllItems() as $item): ?>
	
	if($item->getParentItemId()) {
		continue;
	}
		
	$product = Mage::getModel('catalog/product')->load($item->getProductId());
	$totalProfit += (float) $product->getData('profit');

}

echo $totalProfit;

?>

You should define variables before using them ie. $totalProfit = 0;
You need to cast the profit to a float. There are caveats with using float arithmetic in php in regards to rounding. Therefore, I would suggest using bc math but for this purpose I don't think it will be an issue and installing bc match might not be possible for you.


#15

Here's something that doesn't work:

<?php $sum = 0;?>
<?php foreach($order->getAllItems() as $key => $product): ?>
<?php if($item->getParentItemId()) continue;?>
<?php $product = Mage::getModel('catalog/product')->load($item->getProductId()); ?>
<?php $sum += $product;?>
<?php endforeach;?>
<?php foreach($order->getAllItems() as $item => $value): ?>


#16

i don't see the problem

https://3v4l.org/o5CVY


#17

Can you expand on that? Doesn't really give anyone enough to go on.


#18

Here's what I have now with the code I got above from chorn and my code:

With my test cart it should output this:

15.34 x 3
3.99
3.63

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
    $order = Mage::getSingleton('sales/order');
    $order->loadByIncrementId(
      Mage::getSingleton('checkout/session')->getLastRealOrderId()
    );
    $totalData = $order->getData();
    $allitems = $order->getAllVisibleItems();

foreach($order->getAllItems() as $item): 
      if($item->getParentItemId()) continue; 
          $product = Mage::getModel('catalog/product')->load($item->getProductId()); 
      echo $product->getData('profit'); 
 endforeach;
 ?>

RESULT:
15.3400
3.9900
3.6300


<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
    $order = Mage::getSingleton('sales/order');
    $order->loadByIncrementId(
      Mage::getSingleton('checkout/session')->getLastRealOrderId()
    );
    $totalData = $order->getData();
    $allitems = $order->getAllVisibleItems();

$totalprofit = 0;
foreach($order->getAllItems() as $item): 
    $product = Mage::getModel('catalog/product')->load($item->getProductId());
    $profit = $product->getData('profit');
    $totalprofit += $profit['total'];
    echo $profit['total'], "\n";
endforeach;
echo $totalprofit, "\n";
?>

RESULT:
1
3
3
7


#19

I cited changes in my last post which would fix your problem but that have not been applied.


#20

@ZooKeeper

I apologize. Been very busy.

Getting very close. Here's what I got now:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
    $order = Mage::getSingleton('sales/order');
    $order->loadByIncrementId(
      Mage::getSingleton('checkout/session')->getLastRealOrderId()
    );
    $totalData = $order->getData();
    $allitems = $order->getAllVisibleItems();


foreach($order->getAllItems() as $item): 
      if($item->getParentItemId()) continue; 
          $product = Mage::getModel('catalog/product')->load($item->getProductId());
		  $totalProfit += (float) $product->getData('profit');
endforeach;
echo $totalProfit;
?>

RESULT:
22.96


With my test cart is:

15.34 x 3 (three of these)
3.99
3.63

It working except it's not adding the items if there is more than one of a certain item.

Thank you