我正在做一个基于两个.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
teste3
data.txt中:
12-12
18-12
12-12
12-12
答案 0 :(得分: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";
}
另一种方法是将两个数组合并为一个 但是这有一个缺陷,你不能有两个同名的人。
$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";
}
答案 1 :(得分: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>';
}
?>