【发布时间】:2021-08-26 20:36:16
【问题描述】:
我需要使用 PHP 查找和替换 CSV 行的所有值;
我正在尝试这个,但它甚至将标题替换为 0 并且行值并没有像预期的那样翻倍。
public function checkForNumericValues()
{
// Read the columns and detect numeric values
if (($this->handle = fopen($this->csvFile, "r")) !== FALSE)
{
$fhandle = fopen($this->csvFile,"r");
$content = fread($fhandle,filesize($this->csvFile));
while (($this->data = fgetcsv($this->handle, 1000, ",")) !== FALSE)
{
$this->num = count($this->data);
// Skipping the header
if($this->row == 1)
{
$this->row++;
continue;
}
$this->row++;
// Check and replace the numeric values
for ($j=0; $j < $this->num; $j++)
{
if(is_numeric($this->data[$j]))
{
$content = str_replace($this->data[$j], $this->data[$j] * 2, $content);
}
else
{
$content = str_replace($this->data[$j], 0, $content);
}
}
break;
// print_r($content);
}
$fhandle = fopen($this->csvFile,"w");
fwrite($fhandle,$content);
fclose($this->handle);
}
echo "Numeric and String values been changed in rows of the CSV!";
}
【问题讨论】:
-
文件为什么要打开两次?
-
$this-row的初始值是多少? -
为什么要为应该是临时变量的东西使用类属性,比如
$this->num和$this->handle? -
break语句在文件的第一行之后中断。为什么?