dA_uNknOwN
dA_uNknOwN

Reputation: 981

Split a Comma Separated Value of a Field

I am trying to import a CSV for a shop, with a subset of data from an existing CSV file. I need to split one item from a column (column 3, category_id) that contains multiple comma-separated values, then combine it with one other column (Product_id) to produce multiple rows in the import CSV. See the following examples.

Original CSV

Product_id;article_id;category_id;
"1";"0001";"2,4,6"

Need it into a new CSV file

Product_id;category_id    
"1";"2"    
"1","4"    
"1","6"

I tried just the fegetcsv function to read in the CSV and to printout the whole into an array but I have no idea what to do next.

<?php
$handle = fopen ("articles.csv","r");
while ( ($data = fgetcsv ($handle, 1000, ";")) !== FALSE ) {
$column3[] = $data[3];
}
fclose ($handle);
//edit:
print_r($column3);
?> 

I get:

Array ([0] => category_id [1] => 1 [2] => 0001 [3] => 2,4,6

Upvotes: 1

Views: 1465

Answers (1)

MiDri
MiDri

Reputation: 747

Quick and dirty:

$csvData = file('articles.csv');
$matches = array();
$output = "";
foreach($csvData as $csvLine) {
    if(preg_match('/"(.+)";".+";"(.+)"/', $csvLine, $matches))
    {
        $numbers = explode(',', $matches[2]);
        foreach($numbers as $number) {
            $output .= "\"{$matches[1]}\";\"{$number}\"" . PHP_EOL;
        }
    }
}

Upvotes: 2

Related Questions