PHP循环 - 跳过某些行
问题描述:
我有一个超过100,000行的非常大的文本文件。我需要收集/跳过设定数量的线路:循环线路1-100,跳过线路101-150,读取线路151-210,跳过线路211-300(例如)。PHP循环 - 跳过某些行
我有以下代码
$lines = file('file.txt');
$counter = 0;
foreach ($lines as $lineNumber => $line) {
$counter++;
if ($counter < 101) {
//Do update stuff
}
if ($counter < 102 && $counter > 151) {
//Skip these lines
}
if ($counter < 152 && $counter > 211) {
//Do update stuff
}
}
有没有更好的方式来跳过一个阵列输出的多行?
答
首先,移动到fgets
,这是内存有效的方式。你不需要在内存中拥有所有的数组。至于条件,只需将您的所有条件与or
运营商相结合,不要添加跳过条件,这是没用的。
if ($counter < 101 || ($counter >= 151 && $counter <= 210) || add another pediods here) {
//Do update stuff
}
P.S.你在你的条件中有一个错误,($counter < 102 && $counter > 151)
总是false
以及另一个。
不是一个好主意,在内存中有一个大文件 –
不要在这种情况下使用foreach,使用和利用计数器 – clearshot66
用'fread'逐行读取文件 –