phpforeach循环与计数器,以防止第一行和最后一行的回声


php foreach cycle with counter to prevent echo of first and last lines

我正在尝试制作一个小脚本来操作具有给定目录文件内容的txt文件。发生的情况是,通过进入Win命令行并执行"dir>file.txt"生成的文本文件中有一些行对这个目的来说是垃圾。。。如前7行和后3行。这些:

O volume na unidade C nao tem nome.
O numero de serie do volume - F879-0704
Directorio de C:'xampp'htdocs'projectX'images'
06-01-2012  14:56    <DIR>          .
06-01-2012  14:56    <DIR>          ..
.
.
.
140 ficheiro(s)        5.676.057 bytes
2 dir(s)        307.888.893.952 bytes livres

到目前为止,我的代码是:

$file = $_GET['file'];
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);
$end = 0;
$i = 0;
while($end != 1) {
$output = str_replace("'t|'t", " | ", $data);
$output = explode("'n", $output);
foreach($output as $var) {
    if($i > 7){
      $newstring = substr($var, 36);
      echo "File: " . $newstring . "<br />"; 
    }
    $i++;
}       
echo "<br /><strong>End of file list!</strong>";
$end = 1;

}

我的问题:如何让这个foreach循环也忽略文本文件的最后一行?

您可能应该使用scandir()或专门为此而设计的等效PHP函数。

但是,如果您坚持,您可以使用array_slice()对阵列进行切片。下面将删除第一行和最后一行。

$output = array_slice($output, 2, count($output) - 4);

或者,您可以使用for循环而不是foreach循环来迭代您想要的部分。

$files = (count($output)-2);
for ($file=7; $file < $files; $file++)
  $newstring = substr($output[$file, 36);
  echo "File: " . $newstring . "<br />"; 
}

我想你可以这样做:

$total = count($output);
foreach($output as $var) {
    if ($i > 7 && $i < $total - 1) {
        $newstring = substr($var, 36);
        echo "File: ".$newstring."<br />";
    }
    $i++;
}

不过,我同意@Jason McCreary对这个问题的评论。这不是一个优雅的解决方案。但这对你的具体情况是有帮助的。或者,如果您没有被迫从文本文件中工作,您可以按照opendir()函数的代码示例,以这种方式解析目录内容。

使用array_slice()将$output数组分解为循环前所需的条目。

您可以围绕if语句修改代码,使其看起来像这样:

$total = count($output) - 3;
if($i > 7 && $i < $total) {

我会将所有行存储到一个数组中,拼接出所需的行,然后全部回显。

//ADD FILE LINES TO ARRAY
foreach($output as $var) {
   $file_lines[] = substr($var, 36)."'n"; 
}
//SPLICE OUT LINES NEEDED
$newlines = array_splice($file_lines, 7, count($file_lines)-3);
//ECHO DATA
foreach($newlines as $line) {
   echo $line;
}  

试试这个:

$lastLine=count($output)-3;
for($i=7; $i<$lastLine; $i++) {
    $newstring = substr($var, 36);
    echo "File: " . $newstring . "<br />"; 
} 

您还可以在php代码的帮助下列出指定目录的文件http://www.php.net/manual/en/class.dir.php.