【问题标题】:How to use array_diff for (.txt) files in PHP如何在 PHP 中对 (.txt) 文件使用 array_diff
【发布时间】:2017-04-28 19:36:00
【问题描述】:
<?php
$new = array("12", "11", "10", "9", "8", "7", "6", "5", "4");
$old = array("10", "9", "8", "7", "6", "5", "4", "3", "2", "1");

$result = array_diff($new, $old);

print_r($result);
?>

结果是 Array ( [0] =&gt; 12 [1] =&gt; 11 ) 所以 12 and 11

根据这个例子,如何在 PHP 中使用 array_diff 处理 (.txt) 文件

以下是 (.txt) 示例:

新建 (.txt) 文件

Something here12
Something here11
Something here10
Something here9
Something here8
Something here7
Something here6
Something here5
Something here4
Something here3

旧 (.txt) 文件

Something here10
Something here9
Something here8
Something here7
Something here6
Something here5
Something here4
Something here3
Something here2
Something here1

输出 (.txt) 文件

Something here12
Something here11

【问题讨论】:

  • 将文件读入数组,然后对它们使用array_diff...
  • array_diff(file('new.txt'), file('old.txt')); 就是这样......

标签: php array-difference


【解决方案1】:

您只需要从文本文件中重现您的数组:

<?php
$new = explode(PHP_EOL, file_get_contents('new.txt').PHP_EOL);
$old = explode(PHP_EOL, file_get_contents('old.txt').PHP_EOL);
$result = array_diff($new, $old);

$output= fopen("Output.txt", "w") or die("Unable to open file!");
foreach($result as $value){
    fwrite($output, $value.PHP_EOL);
}

?>

我不确定您是否想要去掉“这里的东西”,但在您的示例 output.txt 中似乎不是。

【讨论】:

  • 它给出了不同的结果:/
  • 您不需要添加PHP_EOL,因为file() 包含换行符,除非您使用FILE_IGNORE_NEW_LINES 选项。
  • @barmar 但输出不同。输出应该是 12, 11
  • @lou 需要删除 txt 的最后一行吗? PHP_EOL 在文本末尾添加空行。 $fp = preg_replace('/^[ \t]*[\r\n]+/m', '', $fp); $fp = preg_replace('/[\r\n]+$/', '', $fp);这些都行不通
  • @Andrew $new = file_get_contents('new.txt', FILE_IGNORE_NEW_LINES);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
相关资源
最近更新 更多