This code creates an array and adds attribute 'payment_sum' even if $value['CardCode'] != $prevCode is false. You can see that I'm printing the values for testing, the last line with 509.85 summing correctly, but the array before that should have been omitted according to this if statement.
if (($handle = fopen('upload/BEN-new.csv', "r")) === FALSE) {
die('Error opening file');
}
$headers = fgetcsv($handle, 1024, ',');
$cardCodes = array();
$payments = array();
$details = array ();
while ($row = fgetcsv($handle, 1024, ",")) {
$cardCodes[] = array_combine($headers, $row);
}
$prevCode = '';
foreach ($cardCodes as $key => $value) {
if ($value['CardCode'] != $prevCode) {
$payments['payment_sum'] = $value['InvPayAmnt'];
}
else {
$payments['payment_sum'] += $value['InvPayAmnt'];
}
$prevCode = $value['CardCode'];
print_r ($payments);
}
fclose($handle);
Printing...
Array
(
[payment_sum] => 1055.40
)
Array
(
[payment_sum] => 550.00
)
Array
(
[payment_sum] => 100.00
)
Array
(
[payment_sum] => 287.33
)
Array
(
[payment_sum] => 509.85
)
Preferred Output
Array
(
[payment_sum] => 1055.40
)
Array
(
[payment_sum] => 550.00
)
Array
(
[payment_sum] => 100.00
)
Array
(
[payment_sum] => 509.85
Array (
[currTotal] => 287.33
[currTotal] => 222.52
)
)
CSV
BENV1072 1055.4
BENV1073 550
BENV5271 100
BENV5635 287.33
BENV5635 222.52
BENV5635? For example, if you addBENV5627 23.54to your input file, the "total" payments will be23.54. Is that really what you want?