PHP replace data only in one column of csv

2019-09-14 11:51发布

问题:

I need to replace the values only from the third column in my csv. And no where else. Column 3 of my csv contains only a 'J' or a'N' and i need to change them to '5' or '0'. But right now i it changes always all found N's and J#s in the whole file. But i need it only updated in the third column.

I use the following code to open and rewrite my csv. But it writes always all found Letters to 5 or 0.

$csvfile = 'csvfile.csv';
if (file_exists($csvfile)) {
        unlink($csvfile);
    echo "Alte $csvfile entfernt!";
} else {
    echo "Keine alte $csvfile vorhanden";
}

$row = 0;
$fp = fopen('csvfile.csv', 'w');
if (($handle = fopen("oldCSV.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 200000, ",")) !== FALSE) {
    $num = count($data);
    $dataold = ['J', 'N'];                                                            
    $datanew = ['5', '0'];
    echo "<p> $num Felder in Zeile $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        fputs($fp, str_replace($dataold, $datanew, $data[$c] . "\n"));
    }
  }
}

fclose($fp);

回答1:

while ($data = fgetcsv($handle)) {

    $data[2] = str_replace(['J', 'N'], ['5', '0'], $data[2]);

    fputcsv($fp, $data);

    echo "<p> ".count($data)." Felder in Zeile ".$row++.": <br /></p>\n";
}

EDIT

  1. I removed !== FALSE part from while to not compare result with false each time, finally fgetcsv() will return false itself and stop the loop
  2. collapsed str_replace and its' arguments-arrays (for readability only)
  3. removed for loop to change only 3rd ([2]) coloumn
  4. got rid of $num variable


回答2:

Lot's of ways and you might get lots of answers. Here's one:

switch($data[2]) {
    case 'J':
        $data[2] = '5';
        break;
    case 'N':
        $data[2] = '0';
        break;
}
fputcsv($fp, $data);


回答3:

You're looping through each column of your CSV. Why not just deal with the specific column? A simple ternary could do this

$data[2] = ($data[2] == 'J') ? '5' : '0'; 


标签: php csv replace