Skip to content
Advertisement

Access, transpose, and join data from a .csv file

I have a CSV File which is laid out as so:

Column1     Column2    Column3
34            56          7
45            55         10
34            40         12

My code:

$row=1
if (($handle = fopen("report.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if($row == 1){ $row++; continue; }
        $num = count($data);
        $row++;

                
        $column1 = $column1 . ", ". $data[1];
        $column2 = $column2 . ", ". $data[2];
        $column3 = $column3 . ", ". $data[3];
    


}
fclose($handle);
}

$column1 = ltrim ($column1 ,','); //removes first comma from string
$column2 = ltrim ($column2 ,',');
$column3 = ltrim ($column3 ,',');

This produces three strings, which are needed to plot a graph.

"34,45,34"
"56,55,40"
"7,10,12"

However it is likely that I will be adding more columns to the csv file, so I need a way of looping around to avoid having to manually add new lines each time. I cannot seem to find a way to perform a loop which would give the variable names automatically for the columns without it breaking.

Advertisement

Answer

Use an array of strings for columns instead of $column1,2,3..:

    ...
    $num = count($data);
    $row++;

    for($i=0; $i<$num; $i++){
        $columns[$i] = $columns[$i] . ", ". $data[$i];
    }
    ...
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement