sohar Posted February 29, 2012 Share Posted February 29, 2012 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! Quote Link to comment https://forums.phpfreaks.com/topic/257984-totals-from-multi-dimensional-array/ Share on other sites More sharing options...
ManiacDan Posted February 29, 2012 Share Posted February 29, 2012 $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}"; Quote Link to comment https://forums.phpfreaks.com/topic/257984-totals-from-multi-dimensional-array/#findComment-1322336 Share on other sites More sharing options...
ManiacDan Posted February 29, 2012 Share Posted February 29, 2012 Also, you may be interested in file as well as file_get_contents Quote Link to comment https://forums.phpfreaks.com/topic/257984-totals-from-multi-dimensional-array/#findComment-1322338 Share on other sites More sharing options...
sohar Posted February 29, 2012 Author Share Posted February 29, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/257984-totals-from-multi-dimensional-array/#findComment-1322344 Share on other sites More sharing options...
ManiacDan Posted February 29, 2012 Share Posted February 29, 2012 Don't suppress warnings, fix them. You were probably trying to process a blank line, which you could skip by adding this to the first line of your loop: if ( trim($var) == '' ) continue; Quote Link to comment https://forums.phpfreaks.com/topic/257984-totals-from-multi-dimensional-array/#findComment-1322351 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.