The reason for the conditional statement evaluating to false has to do with the fact that you simply push a new array into $sheetData
.
$sheetData
looks something like the following in the process:
$sheetData = [
0 => [
'invoice' => 'some_value',
'soId' => '1234',
....
]
];
Thus whenever the test for isset($sheetData['soId'])
is evaluated, it evaluates to false. Because 'soId'
is not directly set on $sheetData
but on one of the nested arrays (in the example index 0).
So, what I personally would do or recommend is to create a small mapping. This mapping will be used to relate the unique identifier soId to an array index.
Whenever we first encounter a new soId we will thus push it onto the result array, followed by mapping the soId to its index.
This allows us to access the array index in constant time and to update the respective sums as such.
Please see the following example:
$map = [];
$sheetData = [];
foreach ($sheet as $row) {
$soId = $row['B'];
// Since there seemed to be presence of thousand separated numbers
// we remove the separation symbol and convert it to a floatval first.
$salePrice = floatval(str_replace(',', '', $row['K']));
$unitCost = floatval(str_replace(',', '', $row['L']));
$margin = floatval(str_replace(',', '', $row['M']));
if (!key_exists($soId, $map)) {
// For simplicity let's rename the fields the first
// time we encounter the soId.
$row = array(
'invoice' => $row['A'],
'soId' => $soId,
'invoiceId' => $row['C'],
'client' => $row['E'],
'salePrice' => $salePrice,
'unitCost' => $unitCost,
'margin' => $margin,
'extInvoice' => $row['Q']
);
// Array push gives us back the number of items,
// hence - 1 is the index in the result array.
$index = array_push($sheetData, $row) - 1;
// For constant time access we track where we
// stored the soId in the sheetData array.
$map[$soId] = $index;
continue;
}
// Otherwise we just add the values to the running totals.
$sheetData[$map[$soId]]['salePrice'] += $salePrice;
$sheetData[$map[$soId]]['unitCost'] += $unitCost;
$sheetData[$map[$soId]]['margin'] += $margin;
}
echo '<pre>';
print_r($sheetData);
echo '</pre>';
The output:
Array
(
[0] => Array
(
[invoice] => 1/3/2021
[soId] => 10556
[invoiceId] => 6963
[client] => AMAZON - D
[salePrice] => 218.98
[unitCost] => 94.05
[margin] => 124.93
[extInvoice] => 111-327***
)
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…