【问题标题】:Read from one and write to another one csv file - PHP从一个读取并写入另一个 csv 文件 - PHP
【发布时间】:2019-05-20 18:30:11
【问题描述】:

我有 CSV 文件:

test2.csv

ID  Name    Price
Q4  Quail   400
Q2  Quail   500
Q1  Quail   100

我用PHP打开这个文件,检查一些条件,如果价格更大或更小,保存新价格,然后我想用php将它放在一个新的CSV文件中。

这是我的代码:

$file = fopen('test2.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
   if (array_key_exists($line[0], $result)) {
        $oldPrice= 500;
        $oldPriceplus20= $oldPrice +($oldPrice*0.2);
        $oldPriceminus20= $oldPrice -($oldPrice*0.2);
        $newPrice = $line[2];
        print( "The 'first' element is in the array\nOld price is: ".$oldPrice."\nNew price is:".$newPrice."\n");
        print("Old price with +20% is:".$oldPriceplus20."\nOld price with -20% is:".$oldPriceminus20."\n");     
        if ($newPrice <= $oldPriceplus20 && $newPrice >= $oldPriceminus20){
            echo"Take new price\n\n";
        }
        else{
            $line[2] = $oldPrice;
            echo"Take the old price.\n";

        }

    }
    $fp = fopen('write.csv', 'w');
    foreach ($line as $lin) {
        fputcsv($fp, array($lin), ',', ' ');
    }
    fclose($fp);
}
fclose($file);

但这是我得到的输出:

Q1
Quail
100

我哪里做错了?如果需要,我的新 CSV 文件应该与 test2.csv 几乎相同,只是带有新价格。

【问题讨论】:

    标签: php excel csv


    【解决方案1】:

    问题是您正在覆盖输出文件并写入输入文件的每个元素,就好像它是文件中的一行一样。此版本在开始时打开输出文件,然后在处理时添加每一行...

    $file = fopen('test2.csv', 'r');
    $fp = fopen('write.csv', 'w');
    while (($line = fgetcsv($file)) !== FALSE) {
        if (array_key_exists($line[0], $result)) {
            $oldPrice= 500;
            $oldPriceplus20= $oldPrice +($oldPrice*0.2);
            $oldPriceminus20= $oldPrice -($oldPrice*0.2);
            $newPrice = $line[2];
            print( "The 'first' element is in the array\nOld price is: ".$oldPrice."\nNew price is:".$newPrice."\n");
            print("Old price with +20% is:".$oldPriceplus20."\nOld price with -20% is:".$oldPriceminus20."\n");
            if ($newPrice <= $oldPriceplus20 && $newPrice >= $oldPriceminus20){
                echo"Take new price\n\n";
            }
            else{
                $line[2] = $oldPrice;
                echo"Take the old price.\n";
    
            }
    
        }
        fputcsv($fp, $line, ',', ' ');
    }
    fclose($file);
    fclose($fp);
    

    【讨论】:

      猜你喜欢
      • 2021-01-23
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多