如何在PHP中检查CSV文件的特定列中的特定值并进行替换。

huangapple go评论54阅读模式
英文:

How to check specific value and replace in specific column of a csv file in php

问题

以下是翻译好的内容:

  1. 在 PHP 中检查 CSV 文件的特定列中的特定值并替换
  2. 在列 B 中检查 USA
  3. 将列 B 中的 USA 替换为新值 India

已尝试下面的代码但未成功:

$lines = file("csvfile.csv", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = array_map("str_getcsv", $lines);

$input = ["row" => 1, "column" => 1];
$lines[$input["row"]][$input["column"]] = "USA";

$fp = fopen('csvfile.csv', 'w');

foreach ($lines as $line) {
    if ($line[1] == 'USA') {
        echo "存在";
        $line[1] = 'India';
    }
    fputcsv($fp, $line);
}
fclose($fp);

我是新手,请帮助。

在 Barmar 先生的帮助下,我获得了结果,但数据应该存在于列 A。

英文:

How to check specific value and replace in specific column of a csv file in php

  1. USA in col B
  2. check USA in col B
  3. Replace with new value India in Col B

Have tried with below code but not successful.

$lines = file("csvfile.csv", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $lines = array_map("str_getcsv", $lines);
	
	$input = ["row" => 1, "column" => 1];
    $lines[$input["row"]][$input["column"]] = "USA";
	
	$fp = fopen('csvfile.csv', 'w');
	
	foreach ($lines as $line) {
    if ($line[1] == 'USA') {
		echo "exist";
        $line[1] = 'India';
    }
    fputcsv($fp, $line);
}
	fclose($fp);

I am new in php,please help

With the help of
Barmar Sir, I got the result.but data should have available in col A.

答案1

得分: 2

foreach循环中,在写入输出文件之前进行替换操作。

遍历行中的所有字段,如果匹配则替换。

foreach ($lines as $line) {
    for ($i = 0; $i < count($line); $i++) {
        if ($line[$i] == 'USA') {
            $line[$i] = 'India';
        }
    }
    fputcsv($fp, $line);
}
英文:

Do the replacement in the foreach loop, before writing to the output file.

Loop through all the fields in the line, replacing it if it matches.

foreach ($lines as $line) {
    for ($i = 0; $i &lt; count($line); $i++) {
        if ($line[$i] == &#39;USA&#39;) {
            $line[$i] = &#39;India&#39;;
        }
    }
    fputcsv($fp, $line);
}

huangapple
  • 本文由 发表于 2023年5月25日 02:14:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76326381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定