|
<?PHP |
|
//comma delimiter |
|
$comma = ","; |
|
//quotation marks |
|
$quotes = "\""; |
|
//we are outputting this on web browser so new line = <br/> |
|
$newLine = "<br/>"; |
|
|
|
//read csv |
|
$file_handle = fopen("test.csv", "r"); |
|
|
|
//iterate through each line of csv file |
|
while (!feof($file_handle)) { |
|
$line_of_text = fgetcsv($file_handle, 1024); |
|
$csvLine = $line_of_text[0]; |
|
|
|
//turn into array |
|
$item = explode(',', $csvLine); |
|
$indexCount = count($item); |
|
|
|
//go through each one of the related items |
|
for ($i = 0; $i < $indexCount; $i++) { |
|
|
|
//shift current value to end of array if you are past first one |
|
//has to be placed here at top of for loop |
|
if ($i > 0) { |
|
$item[$indexCount] = array_shift($item); |
|
} |
|
|
|
//iterate through each item to write next column |
|
foreach ($item as $key => $sku) { |
|
|
|
//apply this only to items with more than 2 related products |
|
//because of the comma quote closure issue |
|
if ($indexCount > 2) { |
|
|
|
//if its first key put it in column A |
|
if ($key == 0) { |
|
echo $sku . $comma; |
|
} |
|
|
|
//next one goes in column B |
|
elseif ($key == 1) { |
|
echo $quotes . $sku . $comma; |
|
} |
|
//if it is past first one and less than or equal to last one |
|
elseif ($key > 1 && $key <= $indexCount) { |
|
|
|
//if it is past first one but not at the end |
|
//we do this because we do not need quote |
|
echo $sku; |
|
|
|
//as long as key is 1 less than the last one seperate it by comma |
|
//because we do not want comma at the end if there is no more after |
|
if ($key < $indexCount - 1) { |
|
echo $comma; |
|
} |
|
|
|
} |
|
} |
|
|
|
//if its only 2 items that should be related |
|
else { |
|
|
|
//if it is the last one or less |
|
//this is in column A |
|
if ($key <= $indexCount) { |
|
echo $sku; |
|
|
|
} |
|
|
|
//as long as it is less than one before the last one |
|
//this is in column B |
|
if ($key < $indexCount - 1) { |
|
echo $comma . $quotes; |
|
} |
|
|
|
|
|
} |
|
|
|
} |
|
|
|
//finished with current item next line foreach ends here |
|
echo $quotes . $newLine; |
|
} |
|
|
|
} |
|
|
|
//done after all lines were iterated in while loop |
|
fclose($file_handle); |