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
Each time through the
forloop you either set$payments['payment_sum']to the current row’s payment ($value['InvPayAmnt']) or you add the row’s payment to the total. Since the previous code is different from the current row’s code for all but the final row, you’re overwriting the running total over and over. Only the last row is added to the previous row’s payment, giving509.85as the result.You are treating
$paymentsas a single-value variable rather than an array because the key under which you store the totals never changes. You need to use the vendor ID as the key.Output
You can easily have the
$paymentsarray track the individual payments from the file as well as the total.