Daniel Zetterström Daniel Zetterström - 3 months ago 21
PHP Question

PHP: csv remodelling

I'm a newbie trying code, and have an issue that i can not get my head around and would appreciate some help.

I have Csv's file looks something like this (always id,url but the amount of urls / id differ):

12345,wwwurl1
12345,wwwurl2
12345,wwwurl3
12346,wwwurl1
12347,wwwurl1
12347,wwwurl2
...,... and so on


How to make this look like this, easier to show than explain i think :)

12345,"wwwurl1,wwwurl2,wwwurl3"
12346,"wwwurl1"
12347,"wwwurl1,wwwurl2"
...,"...,..." and so on


Basically only one row per id, all urls added with comma separator.

All help is appreciated!

Answer
<?php

$file = fopen(__DIR__ . '\\' . 'test.csv', 'r+');//your file
$fileResult = fopen(__DIR__ . '\\' . 'result.csv', 'w+');//result file
$rowInfo = [];
while (($data = fgetcsv($file, 0, ",")) !== FALSE) {
    $rowInfo[$data[0]] .= $data[1] . ',';
}

foreach ($rowInfo as $key => $value) {
    fputcsv($fileResult,[$key,rtrim($value, ",")]);
}

fclose($file);
fclose($fileResult);
Comments