下面介绍目录中的文件,读取它们并将它们保存在最多500行的文件中到新目录。 这对我很有用(感谢Daniel)但是,我需要修改。 我想保存到基于alpha num的文件。
首先,以数字方式对数组进行排序(已经是小写)将是我假设的第一步。
抓住每个$ incoming中的所有行。“/。txt”以“a”开头并将它们放入$ save500的文件夹中。“/ a”但是,每行最多500行。 (我想最好从排序顶部的第一个开始,所以“0”不是“a”对吗?)
所有以数字开头的行都进入$ save500。“/ num”。
除了a-z0-9之外,所有行都不会以任何内容开头。
这将允许我使用此flatfile方法更有效地搜索我的文件以获得匹配。将其缩小到一个文件夹。
$nextfile=0;
if (glob("" . $incoming . "/*.txt") != false){
$nextfile = count(glob("" . $save500 . "/*.txt"));
$nextfile++;
}
else{$nextfile = 1;}
/**/
$files = glob($incoming."/*.txt");
$lines = array();
foreach($files as $file){
$lines = array_merge($lines, file($file, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
}
$lines = array_unique($lines);
/*this would put them all in one file*/
/*file_put_contents($dirname."/done/allofthem.txt", implode("\n", $lines));*/
/*this breaks them into files of 500*/
foreach (array_chunk($lines, 500) as $chunk){
file_put_contents($save500 . "/" . $nextfile . ".txt", implode("\n", $chunk));
$nextfile++;
}
每个仍然需要最多500行。
我稍后会毕业到mysql。现在只做了几个月。
好像这还不够。我甚至想过取下前两个角色。使用subs a / 0到z / z创建目录!
由于没有回复,可能是错误的做法。
但我想像aardvark这样的词保存到1.txt a / a文件夹(追加)。除非1.txt有500行,否则将其保存到/ a 2.txt。
因此xenia将被附加到x / e文件夹1.txt文件,除非有500行,所以创建2.txt并将其保存在那里。
然后,我将能够更有效地搜索这些单词,而无需将内容加载到内存中或循环遍历不包含匹配项的文件/行。
谢谢大家!
答案 0 :(得分:1)
我在这里写了一些代码,应该做你正在寻找的东西,它不是一个性能美,但应该做的工作。在安全的环境中试用,不保证任何数据丢失;)
评论是否有任何错误,这里已经很晚了;)我必须睡一觉;)
注意:只有每行至少有2个字符时才能使用此功能! ;)
$nextfile=0;
if (glob("" . $incoming . "/*.txt") != false){
$nextfile = count(glob("" . $save500 . "/*.txt"));
$nextfile++;
}
else
{
$nextfile = 1;
}
$files = glob($incoming."/*.txt");
$lines = array();
foreach($files as $file){
$lines = array_merge($lines, file($file, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
}
$lines = array_unique($lines);
/*this would put them all in one file*/
/*file_put_contents($dirname."/done/allofthem.txt", implode("\n", $lines));*/
/*this breaks them into files of 500*/
// sort array
sort($lines);
// outer grouping
$groups = groupArray($lines, 0);
$group_keys = array_keys($groups);
foreach($group_keys as $cKey) {
// inner grouping
$groups[$cKey] = groupArray($groups[$cKey], 1);
foreach($groups[$cKey] as $innerKey => $innerArray) {
$nextfile = 1;
foreach(array_chunk($innerArray, 500) as $chunk) {
file_put_contents($save500 . "/" . $cKey . "/" . $innerKey . "/" . $nextfile . ".txt", implode("\n", $chunk));
$nextfile++;
}
}
}
function groupArray($data, $offset) {
$grouped = array();
foreach($data as $cLine) {
$key = substr($cLine, $offset, 1);
if(!isset($grouped[$key])) {
$grouped[$key] = array($cLine);
}
else
{
$grouped[$key][] = $cLine;
}
}
return $grouped;
}