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
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}";

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.