I have a CSV file which has many rows in, like the following:
Client Product Quantity Unit Amount Total 1 Prod1 1 10 10 1 Prod2 2 15 30 2 Prod1 2 12 24 2 Prod2 1 5 5
etc...
i want to be able to import the CSV file using PHP and group each client together and display the total cost for each client.
I have my import function etc...
if(is_uploaded_file($_FILES['file']['tmp_name'])) {
echo "<h3>" . "File ". $_FILES['file']['name'] ." uploaded successfully." . "</h3><br><br>";
}
$handle = fopen($_FILES['file']['tmp_name'], "r");
fgetcsv($handle);
//then loop through each row
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
}
but im not sure what to do inside the while loop
if possible, i want to do this without using a database
$clients = array();
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if(!array_key_exists($data[0],$clients))
$clients[$data[0]] = array();
array_push($clients[$data[0]],$data);
}
//then loop over each client in your array
foreach($clients as $clientId => $clientEntries)
{
// combine or print records...
}
So your task within the loop is to take the array provided by $data and transform it into a usable array that uses the client id as a key and the total cost as the value. My implementation would be as follows:
$customerTotals = array();
while ($data = fgetcsv($handle, 1000, ',')) {
$currentTotal = isset($customerTotals[$data[0]]) ? intval($customerTotals[$data[0]]) : 0;
$addedTotal = intval($data[2]) * intval($data[4]);
$customerTotals[$data[0]] = $currentTotal + $addedTotal;
}
Please note that the code above does not do any sanity checking. A blank line or missing columns will cause unexpected errors. It puts the first column, the customer id, as the array key, and muliplies the 3rd and 5th columns together, the quantity and price, respectively.
You can now iterate this array like this:
foreach ($customerTotals as $customerId => $total) {}