2017-04-05 51 views
0

我有一个有4个值的数组。我想在文本文件中搜索数组中的值并返回字符串可用的行号。但是,当我的代码执行时,它只给出数组中第一个值的行号,并且还为其余的数组值打印相同的行号。在foreach中使用while循环来获得一个字符串的行号

$scheme_code = array("106212","112422","114239","128053"); 

    $search  = $scheme_code[0]; 

    $i = 0; 
    $line_number = false; 
    $count = 0; 
    $handle = fopen("http://portal.amfiindia.com/spages//NAV0.txt", 'r'); 
    foreach ($scheme_code as $code) { 
     echo $code."<br>"; 
     while (($line = fgets($handle, 4096)) !== FALSE and !$line_number) { 
      $count++; 
      $line_number = (strpos($line, $code) !== FALSE) ? $count : $line_number; 
     } 
     echo "The line number is".$line_number."<br>"; 

     //fclose($handle); 
    } 

我的输出是这样的106212 The line number is 5386 112422 The line number is 5386 114239 The line number is 5386 128053 The line number is 5386

5386 is the line number of the value 106212. 

当我呼应$code。它会打印$code,但第一个代码的行号只会打印其余代码。

回答

0

您需要在while循环外重置$ line_number的值。这是导致不执行while循环的条件。

因此在foreach中声明变量$ line_number。