如何回显.txt的位置?

问题描述 投票:-1回答:2

我正在做一个基于两个.txt的代码,一个带有名字,另一个带有生日。我正在阅读它们,当日期与date.txt重合时,将显示names.txt的重合行中的名称,但是当我进行比较时,只显示names.txt的最后一行。

那是代码:

<?php

    $nome   =   fopen("nome.txt", "r");
    while(!feof($nome)){
        $pessoa =   fgets($nome);
    }   fclose($nome);

    $current    =   date("d-m");
    $content    =   fopen("data.txt", "r");

    while (!feof($content)){
        $linha  = fgets($content);
        if (strtotime($linha)   ==  strtotime($current))   {
            echo $pessoa;
            echo '<br>';
        }
    }   fclose($content);

    ?>

.txt的内容:


nome.txt:

测试

teste1

teste2


data.txt中:

12-12

18-12

12-12

12-12

php date comparison
2个回答
0
投票

您可以同时从两个文件中逐行处理

<?php

    $nome    =   fopen("nome.txt", "r");
    $content =   fopen("data.txt", "r");
    $current =   date("d-m");

    while(!feof($nome) && !feof($content)){
        $pessoa =   fgets($nome);
        $linha  = fgets($content);

        if (trim($current) == trim($linha))   {
            echo $pessoa;
            echo '<br>';
        }
    }   

    fclose($content);
    fclose($nome);

?>

或者您可以使用file function将整个文件读入数组,但这可能会更慢

<?php

    $nome    =   file("nome.txt");
    $content =   file("data.txt");
    $current =   date("d-m");

    foreach($content as $key => $linha)

        if (trim($current) == trim($linha))   {
            echo $nome[$key];
            echo '<br>';
        }

?>

0
投票

您可以打开文件并将它们加载到数组中,并使用foreach和$ key同步输出它们。

$names = explode(PHP_EOL,file_get_contents("none.txt"));

$dates = explode(PHP_EOL,file_get_contents("data.txt"));

Foreach($names as $key => $name){

     Echo $name . " " . $dates[$key] . "\n";
}

https://3v4l.org/59ao6

另一种方法是将两个数组合并为一个。 但是这有一个缺陷,你不能有两个同名的人。

$days = array_combine($names, $dates);
// Days is now an associate array with name as key and date as birthday.
Foreach($days as $name => $date){

     Echo $name . " " . $date . "\n";
}
© www.soinside.com 2019 - 2024. All rights reserved.