Jump to content

totals from multi-dimensional array


sohar

Recommended Posts

I have a pipe delimited file with this sample content:

 

INV8004199|01/26/2012|Next door|648.00

SPT803487|01/25/2012|This and That|3360.00

INV8004193|01/25/2012|Where is it|756.00

INV8004133|01/05/2012|snowy winter|6750.00

 

I open the file to read it:

     $CPfile = "sample.DEL";

      $ft = fopen( $CPfile, "r");
$content1 = fread($ft, filesize($CPfile));
fclose($ft);

 

 

 

Then I loop thru it:

 

	$out = explode("\n",  $content1);
	$total = 0;
   
   foreach($out as $var) {

	$tmp = explode("|", $var);

	for($i=0;$i<count($tmp);$i++){
                            echo $tmp[$i] . "<BR>";
               }
   }

 

 

What I would like to get is the total of all prices (last column) in all lines of the file.  Can someone help please?. Thanks!

Link to comment
https://forums.phpfreaks.com/topic/257984-totals-from-multi-dimensional-array/
Share on other sites

$total = 0;
   foreach($out as $var) {

	$tmp = explode("|", $var);

                $total += $tmp[count($tmp)-1];

	for($i=0;$i<count($tmp);$i++){
                            echo $tmp[$i] . "<BR>";
               }
   }

echo "Grand total: {$total}";

Thank you! works great.

 

One quick follow up. in my original file, the price is 3 steps away from the end actually. i.e.

 

INV8004199|01/26/2012|Next door|648.00|AB|T3

 

I changed your expression to:

 

$total += $tmp[count($tmp)-3];

 

to capture the price value.

 

However, I received a Notice: Undefined offset: -2, which I suppressed by adding

 

error_reporting( E_ALL ^ E_NOTICE );

 

at the beginning of my script.

 

Is this ok?

 

Thanks again.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.