Php 解析两个文件并比较字符串
我有两个文件,格式如下: 第一档Php 解析两个文件并比较字符串,php,arrays,parsing,Php,Arrays,Parsing,我有两个文件,格式如下: 第一档 adam 20 male ben 21 male 第二档 adam blonde adam white ben blonde 我想做的是,在第一个文件中使用adam实例,在第二个文件中搜索它并打印属性 数据由制表符“\t”分隔,因此这是我到目前为止的数据 $firstFile = fopen("file1", "rb"); //opens first file $i=0; $k=0; while (!feof($firstFile) ) { //feof
adam 20 male
ben 21 male
第二档
adam blonde
adam white
ben blonde
我想做的是,在第一个文件中使用adam实例,在第二个文件中搜索它并打印属性
数据由制表符“\t”分隔,因此这是我到目前为止的数据
$firstFile = fopen("file1", "rb"); //opens first file
$i=0;
$k=0;
while (!feof($firstFile) ) { //feof = while not end of file
$firstFileRow = fgets($firstFile); //fgets gets line
$parts = explode("\t", $firstFileRow); //splits line into 3 strings using tab delimiter
$secondFile= fopen("file2", "rb");
$countRow = count($secondFile); //count rows in second file
while ($i<= $countRow){ //while the file still has rows to search
$row = fgets($firstFile); //gets whole row
$parts2 = explode("\t", $row);
if ($parts[0] ==$parts2[0]){
print $parts[0]. " has " . $parts2[1]. "<br>" ; //prints out the 3 parts
$i++;
}
}
}
$firstFile=fopen(“file1”、“rb”)//打开第一个文件
$i=0;
$k=0;
while(!feof($firstFile)){//feof=而不是文件的结尾
$firstFileRow=fgets($firstFile);//fgets获取行
$parts=explode(“\t”,$firstFileRow);//使用制表符分隔符将行拆分为3个字符串
$secondFile=fopen(“file2”、“rb”);
$countRow=count($secondFile);//计算第二个文件中的行数
当($i您在内部循环中有一个输入错误时,您正在读取第一个文件
,应该正在读取第二个文件。此外,在退出内部循环后,您希望将第二个文件
指针重新绕回到开始处。这样如何:
function file2array($filename) {
$file = file($filename);
$result = array();
foreach ($file as $line) {
$attributes = explode("\t", $line);
foreach (array_slice($attributes, 1) as $attribute)
$result[$attributes[0]][] = $attribute;
}
return $result;
}
$a1 = file2array("file1");
$a2 = file2array("file2");
print_r(array_merge_recursive($a1, $a2));
它将输出以下内容:
Array (
[adam] => Array (
[0] => 20
[1] => male
[2] => blonde
[3] => white
)
[ben] => Array (
[0] => 21
[1] => male
[2] => blonde
)
)
但是,如果两个文件都很大(>100MB),这个程序将一块读取两个文件并崩溃。另一方面,90%的php程序都有这个问题,因为file()
很流行:-)如果您的第一个文件不大,我建议将第一个文件读入缓存,然后将第二个文件的内容合并到一个多维数组中。谢谢您的帮助。我没有注意到。我添加了$FIRSTFILERROW[]而不仅仅是$firstFileRow,这帮助我找到了一个soloution。该网站是新的,所以我应该用soloution编辑我的问题吗?如果您对我的答案解决了您的问题感到满意,请勾选,使其看起来已回答。谢谢