在php中的3个文本文件中找到重复的值


find duplicate values in 3 text files in php

我有3个文本文件,请参阅以下

result1.txt
===========
782
778
719
result2.txt
============
130
129
719
result3.txt
============
718
719
585
520

我想以php的形式上传这些文件,然后我想检查所有文件中有多少重复值记住重复意味着所有3个文件都有相同的值是重复的,例如719包含在所有文件中我尝试使用数组,但它不适用于3数组我使用了array_intersect($array1,$array2,$array3);,但它不起作用。有人能帮我吗??

这是我的代码

$a = file('result1.txt');
$b = file('result2.txt');
$c = file('result3.txt');
foreach($a as $key => $value)
{
$a[$key] = $value;
}
foreach($b as $key => $value)
{
$b[$key] = $value;
}
foreach($c as $key => $value)
{ 
$c[$key] = $value;
}
$result=array_intersect($a,$b,$c);
print_r($result);
foreach(array_intersect($a, $b, $c) as $x) { echo $x; }

试试这样的东西:

$hash = array();
// for each input file
$file = new SplFileObject("input_file_name");
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
while (!$file->eof()) {
    $num = (int) $file->fgets();
    if (!array_key_exists($num, $hash)) {
        $hash[$num] = 1;
    } else {
        $hash[$num] += 1;
    }
}
$file = null;
// now we get only the entries with a count of 3
$triples = array_filter($hash, function ($val) { return $val == 3; });
$results = array_keys($triples);

最后,$results将包含在结果集中出现3次的值。

array_intersect()使用以下方法工作良好:

<?php
$array1 = [782,778,719];
$array2 = [130,129,719];
$array3 = [718,719,585,520];
$dupes = array_intersect($array1,$array2,$array3);
echo '<pre>',print_r($dupes),'</pre>';

将文件插入阵列可以通过以下方式完成:

$array1 = readfile('result1.txt');
$array2 = readfile('result3.txt');
$array3 = readfile('result3.txt');