PHP - 如何打开文件并读取它们,然后用“x”写入新文件每个文件的行数?
我之前在这里发布过这个问题,但没有得到回复。我可能做错了什么,所以这里再次提供更多细节。
该目录中的文件名为 1.txt、2.txt、3.txt 等......下面的代码片段进入该目录,打开所有读取它们的 *,txt 文件,删除重复项并创建一个包含所有内容的文件独特的内容。 (本例中的名称)。
$files = glob($dirname."/*.txt"); //matches all text files
$lines = array();
foreach($files as $file)
{
$lines = array_merge($lines, file($file, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
}
$lines = array_unique($lines);
file_put_contents($dirname."/allofthem.txt", implode("\n", $lines));
}
以上对我来说非常有用!感谢 stackoverflow 的大力帮助。
但是,我希望更进一步。
我如何修改上述代码来创建每个新数据最多包含 5oo 行的文件,而不是一个大的重复的免费“allofthem.txt”文件?
他们需要进入一个新目录,例如 $dirname."/done/".$i.".txt" 我曾尝试在循环中计数,但我的努力没有奏效,最终变成了一英里长。
我还尝试将 500 推入一个数组,递增到另一个数组并以这种方式保存。运气不好。我只是没有“明白”它。
同样,这个初学者需要一些专家的帮助。提前致谢。
I posted this question here before but there were no responses. I may have done something wrong so, here it is again with some more details.
The files in the directory are named 1.txt, 2.txt, 3.txt etc.... The snippet below enters that directory, opens all the *,txt files reading them, removes the dupes and creates one file with all the unique contents. (names in this case).
$files = glob($dirname."/*.txt"); //matches all text files
$lines = array();
foreach($files as $file)
{
$lines = array_merge($lines, file($file, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
}
$lines = array_unique($lines);
file_put_contents($dirname."/allofthem.txt", implode("\n", $lines));
}
The above works great for me! Thanks to great help here at stackoverflow.
But, I desire to take it one step further.
Instead of one big duplicate free "allofthem.txt" file, how can I modify the above code to create files with a maximum of 5oo lines each from the new data?
They need to go into a new directory eg $dirname."/done/".$i.".txt" I have tried counting in the loop but my efforts are not working and ended up being a mile long.
I also attempted to push 500 into an array, increment to another array and save that way. No luck. I am just not "getting" it.
Again, this beginner needs some expert assistance. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据代码获得行数组后,您可以使用
array_chunk
,然后将每个块写入自己的文件:Once you have your array of lines as per your code, you can break it into chunks of 500 lines using
array_chunk
, and then write each chunk to its own file:这个功能会让你到达某个地方!
源代码: http://www.php.net/manual/ en/function.md5-file.php#94494
this function will get you somewhere !
Src: http://www.php.net/manual/en/function.md5-file.php#94494