Using PHP to try and tackle this problem, but open to other solutions (Python, Bash, etc).
I have csv data in the following format:
Note: store name id (rows 1 and 6) is always 10 digits
Product id (col1, rows 2,3,4 and 7,8,9,10,11) is always 7 digits.
Store name 0123456789,,,
0123456,product desc,1,1.00
1234567,product desc2,1,2.00
2345678,product desc3,1,3.00
Ship Total,6.00,,
Store name2 9876543210,,,
0123456,product desc,4,1.00
1234567,product desc2,2,2.00
2345678,product desc3,1,3.00
3456789,product desc4,3,4.00
45678901,product desc5,1,5.00
Ship Total,28.00,,
The desired format is:
0123456789,0123456,product desc,1,1.00
0123456789,1234567,product desc2,1,2.00
0123456789,2345678,product desc3,1,3.00
9876543210,0123456,product desc,4,1.00
9876543210,1234567,product desc2,2,2.00
9876543210,2345678,product desc3,1,3.00
9876543210,3456789,product desc4,3,4.00
9876543210,45678901,product desc5,1,5.00
I have a program to parse the data in the above format.
I’ve gotten the stores into an array and the transactions into another array… just need to put them together.
Here’s what I’ve got so far.
$csv = array(); $file = fopen($datafile, 'r'); while (($result = fgetcsv($file)) !== false) { $csv[] = $result; } fclose($file); foreach ($csv as $key => $value) { if (preg_match('/\d{10}$/', $value[0],$store)) { $stores[$key] .= $store[0]; } } print_r($stores); foreach ($csv as $key => $value) { if (preg_match('/^\d{7}/', $value[0],$transaction)) { $transactions[$key] = array("Item"=>$value[0],"Desc"=>$value[1],"Qty"=>$value[2],"Price"=>$value[3]); } } print_r($transactions)print_r results:
Array ( [0] => 0123456789 [5] => 9876543210 ) Array ( [1] => Array ( [Item] => 0123456 [Desc] => product desc [Qty] => 1 [Price] => 1.00 ) ... ... arrays 2,3,4,6,7,8,9.... ... [10] => Array ( [Item] => 45678901 [Desc] => product desc5 [Qty] => 1 [Price] => 5.00 ) )EDIT after answers. Here's what worked perfectly.
[code]
$file = fopen($datafile, 'r'); $txns = array(); $LastStore = ''; while (($result = fgetcsv($file)) !== false) { if (preg_match('/\d{10}$/', $result[0],$store)) { $LastStore = $store; } elseif (preg_match('/[A-Za-z]+/', $result[0])) { continue; } else { $txns[] = array("Store"=>$LastStore[0], "Item"=>$result[0],"Desc"=>$result[1],"Qty"=>$result[2],"Price"=>$result[3]); } } fclose($file);[/code]
I would suggest something like this