简体   繁体   English

PHP字符串比较无法正常工作

[英]PHP String Comparison not working as expected

I have the following snippet of code that I am trying to use to read a file that can have some lines repeated two or more times. 我有以下代码片段,试图用来读取文件,该文件的某些行可以重复两次或更多次。 The goal of this script is to only write unique lines (no duplicates) but for some reason it appears that it is not detecting equality. 该脚本的目标是只写唯一的行(不重复),但由于某种原因,它似乎没有检测到相等性。 Any thoughts? 有什么想法吗?

$handle = @fopen("Old.csv", "r");
$new = @fopen("New.csv", "w");
$last_line = null;

if ($handle && $new) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        if( $last_line != $buffer ) fwrite( $new, $buffer );
        $last_line = $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
    fclose($new);
}

Here is an example of "Old.csv" 这是“ Old.csv”的示例

 apple
 apple
 orange
 grapes
 grapes
 grapes

"New.csv" should be: “ New.csv”应为:

apple
orange
grapes

But it ends up being an exact copy of "Old.csv". 但这最终是“ Old.csv”的精确副本。

try cat old.csv | sort -u > new.csv 尝试cat old.csv | sort -u > new.csv cat old.csv | sort -u > new.csv at the command prompt its much faster. 在命令提示符下cat old.csv | sort -u > new.csv进行cat old.csv | sort -u > new.csv会更快。

Thanks to everyone to replied. 感谢大家的答复。 I did unintentionally leave out a clue which is that I am on a Mac. 我确实无意间遗漏了一个线索,那就是我在Mac上。 I resaved the CSV to use the Windows format and re-ran my script and all is well. 我重新保存了CSV以使用Windows格式,然后重新运行了脚本,一切都很好。 I guess it was the line endings. 我想这是行尾。 Anyhow, the bottom line is that the script works. 无论如何,最重要的是脚本可以正常工作。

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

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