首页 > 解决方案 > 如何将文件拆分为数组,与查询进行比较,然后在上下文中打印?

问题描述

全部。我正在尝试将文件加载为在换行符处拆分的数组,然后打印除以下两行之外的包含查询的行。但是,每当我尝试运行它时,它总是求助于我的 else 语句,即使我知道可以在该特定文件中找到查询。这让我相信存在编码问题,所以我需要你的帮助。先感谢您!


$query = "text";

// reads file into array and splits at line breaks
$array = explode("\n", file_get_contents('files/file2.txt'));

// checks to see if the query is found in the array
// checks if the value of at least one key matches the query
// and, if so, prints the line and next two
if (in_array($query, $array)) {
    foreach ($array as $key => $value) {
        if($value == $search AND $count >= $key+3) {
            echo $array[$key] . $array[$key+1] . $array[$key+2];
        }
    }
} else {
    echo "Match not found.\n";

}

标签: phparraysexplode

解决方案


玩弄这段代码时,唯一可行的方法是,如果任何一行包含单词“text”并且只有单词“text”。尝试这个:

$query = "text";

// reads file into array and splits at line breaks
$array = explode("\n", file_get_contents('files/file2.txt'));


// checks to see if the query is found in the array
// checks if the value of at least one key matches the query
// and, if so, prints the line and next two
$found = false;

// Here's where I made some changes.  
// I added a new foreach loop to go through each line in the array.
foreach ($array as $x) {
// Instead of using the in_array function, I simply searched for 
// the position of the query. If the strpos function returns -1,
// it means that the query hasn't been found.
    if (strpos($x, $query) > -1) {
// If found, set the found flag as true.
        $found = true;
        foreach ($array as $key => $value) {
            if($value == $search AND $count >= $key+3) {
                echo $array[$key] . $array[$key+1] . $array[$key+2];
            }
        }
    } 
}
// If the found flag is false, display the "Match not found" message.
if ($found) {} else {
    echo "Match not found.\n";
}

推荐阅读