简体   繁体   English

PHP仅在csv的一列中替换数据

[英]PHP replace data only in one column of csv

I need to replace the values only from the third column in my csv. 我只需要替换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'. 我的csv的第3列仅包含“ J”或“ N”,我需要将其更改为“ 5”或“ 0”。 But right now i it changes always all found N's and J#s in the whole file. 但是现在我改变了,在整个文件中总是找到所有N和J#。 But i need it only updated in the third column. 但是我只需要在第三栏中进行更新。

I use the following code to open and rewrite my csv. 我使用以下代码打开并重写我的csv。 But it writes always all found Letters to 5 or 0. 但它会将找到的所有字母始终写入5或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);

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);
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 我删除!== FALSE部分从while不比较假,每次导致,终于fgetcsv()将返回false本身并停止循环
  2. collapsed str_replace and its' arguments-arrays (for readability only) 折叠的str_replace及其参数数组(仅出于可读性)
  3. removed for loop to change only 3rd ( [2] ) coloumn 删除for循环以仅更改第三( [2] )列
  4. got rid of $num variable 摆脱了$num变量

You're looping through each column of your CSV. 您正在遍历CSV的每一列。 Why not just deal with the specific column? 为什么不只处理特定的列? A simple ternary could do this 一个简单的三元可以做到这一点

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM