【问题标题】:php change value from file to another filephp将值从文件更改为另一个文件
【发布时间】:2014-04-05 06:54:45
【问题描述】:

我有 2 个文件(A.txt 和 B.txt)。 我想更改/更新文件 A 的信息文件 B。 文件 A 的内容是:

Fish    2   4
Horse   3   2
Chicken 1   5

文件B的内容是:

not 5   2
not 3   2
not 2   2
not 2   4

我想从文件 B 中得到他的结果,像这样:

not 5   2
Horse   3   2
not 2   2
Fish    2   4

我知道它使用表达式“如果”。但我不知道如何编码。有什么可以帮助的吗?在文件中由“tabs”和“newline”分隔

【问题讨论】:

  • Chicken 1 5 怎么了?
  • 忽略,因为在文件中没有 [link](1 15)
  • 这仍然没有意义..你能解释一下你是如何得出结果的吗??
  • 刚刚回复你了,看看对你有没有帮助

标签: php file fopen fgets


【解决方案1】:

试试

<?php

    foreach (file("A.txt") as $line) 
    {
        // Split line
        $field = preg_split('/\s+/',$line);

        // This is your array index
        $index = $field[1].' '.$field[2];

        // Array holds name which is first field
        $Array[$index] = $field[0];
    }

    foreach(file("B.txt") as $line)
    {

        // Split field   
        $field = preg_split('/\s+/',$line);

        // 2nd file index
        $index = $field[1].' '.$field[2];

        // if index is set in array echo name else line
        echo (isset($Array[$index])?$Array[$index].' '.$index:$line).'<br>';
    }
?>

给定输入的结果

 not 5 2
 Horse 3 2
 not 2 2
 Fish 2 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    相关资源
    最近更新 更多