用PHP写读取文本文件1.txt和2.txt中每行的内容,然后将1.txt每行内容随机和2.txt每行内容结合写入3.txt中
发布网友
发布时间:2022-04-30 02:15
我来回答
共2个回答
热心网友
时间:2023-10-05 09:09
/*
php按行读取文件可以用file()函数,结果是一个数组,每个元素是一行带换行符\n的字符串,
trim(字符串,字符)去掉字符串首尾的规定字符,如果不填,则去掉"\0" - NULL,"\t" - tab
"\n" - new line,"\x0B" - 纵向列表符,"\r" - 回车," " - 普通空白字符
*/
$file1 = file("1.txt"); //按行读取1.txt数据,存到数组$file1里
$file2 = file("2.txt");
$file3 = ""; //初始化$file3
$len = sizeof($file2); //file2的长度(也就是行数)
foreach($file1 as $f){ //循环$file1
$f = trim($f);
$i = mt_rand()(0,$len-1); //随机获取一个0到$file2长度-1的数
$f2 = $file[$i]; //获取$file2的一条数据(某一行)
$f2 = trim($f2);
$file3 .= $f.",".$f2."\n"; //拼接字符串
}
if(file_put_contents("3.txt",$file3)){ //将$file3写入文件3.txt
echo "写入成功";
}else{
echo "失败";
}
热心网友
时间:2023-10-05 09:09
<?php
$fp1 = fopen("1.txt", "r");
$fp2 = fopen("2.txt", "r");
$fp3 = fopen("res1.txt","ab");
while(!feof($fp1)) {
$info[] = fgets($fp1, 20);
}
$count = 0;
array_pop($info);
shuffle($info);
while(!feof($fp2)) {
$info[$count] = str_replace("\n", "", $info[$count]);
fwrite($fp3, $info[$count]);
fwrite($fp3, fgets($fp2, 2048));
$count++;
}
fclose($fp1);
fclose($fp2);
fclose($fp3);
?>
刚写的