-1

I need to transpose some values in some csv files that we get sent on a regular basis so that they are able to be imported into a website and I'm not sure the best way to go about doing it.

The data arrives in a csv file with a header row containing the column names, and the first column values are product ID's. The data looks like this…

 ID      F      F-VF     VF      VF-XF     XF
  1     840     960     1080     1248     1944
  2     1137.5  1300    1462.5   1690     2632.5
  3     1225    1400    1575     1820     2835

What I'm looking to do is change this around so the column name and it's value are put into a new line for each value for the same id like so…

 ID    COND     VALUE
 1     F         840
 1     F-VF      960
 1     VF        1080
 1     VF-XF     1248
 1     XF        1944
 2     F         1137.5
 2     F-VF      1300
 2     VF        1462.5
 2     VF-XF     1690
 2     XF        2835

I may also need to add some strings into the cells - is that easy to do?

Thanks a lot

Bassybert
  • 11
  • 3

2 Answers2

0

Not necessarily the most elegant version, just to get an idea.

Something like this would work in case it's a existing csv, which gets read and overwritten with the transposed version.

// assuming a dataset like
// ----
// fruit, apple, pear, peach
// animal, eagle, bear, wolf
// car, renault, fiat, nio
$f = fopen($savePath, 'r');
$header = [];
$data = [];
while($row = fgetcsv($f, 0, ",")) {
    $header[]=$row[0];
    for ($i = 1; $i < sizeof(array_keys($row)); $i++) {
        $data[$i][$row[0]]=$row[$i];                    
    }
}
fclose($f);

$f = fopen($savePath, 'w');

fputcsv($f, $header);
foreach ($data as $recordColDataSet) {
    fputcsv($f, array_values($recordColDataSet));
}

fclose($f);

Transposing arrays could also be something to look at eg in this question here: Transposing multidimensional arrays in PHP

til
  • 832
  • 11
  • 27
-1

Have you tried any of the standard PHP methods like: str_getcsv() or fgetcsv()?

A quick search of "php csv" provides a TON of possible solutions. I suggest trying a few, then reporting back here if you have a specific problem.

Dave
  • 28,833
  • 23
  • 113
  • 183
  • Hi Dave, I have had a look but I'm not sure which function would be the best one, hence my question here. – Bassybert Jan 20 '16 at 17:32
  • @Bassybert, honestly, it feels like you don't want to try. Just click the links I provided, and read their descriptions. It should be pretty obvious. Your question currently has 2 close votes and a comment that insinuates you should re-ask your question. So I'm not alone on this. Normally I would have just put in my own close-vote, but since you're a first-timer to StackOverflow, I'll give you the benefit of the doubt and share these links with you. Hope they help! – Dave Jan 20 '16 at 17:38