比较2个文本文件并获取内部ID

时间:2014-05-31 10:54:58

标签: php for-loop array-difference array-intersect

我尝试将2个文本文件与由-分隔的数据进行比较,在一种情况下,一个文件获取所有数据,在另一种情况下,只有具有相同ID的更改数据,在这种情况下,此文件称为{{ 1}}

两个文件中的结构就是这样:

文件txt(第一个是id)db / text.txt

db_tmp.txt

用于比较的文件,例如有更改的数据,相同的ID但不同的内容 - db_tmp.txt

1a34-Mark Jhonson
1a56-Jhon Smith
1a78-Mary Walter

我创建了一个比较两个文件的函数,以检测是否存在相同的id和更改:

1a56-Tom Tom

如果tmp中存在相同的id,我必须检测另一个文件中的条目并更改为tmp的值,我尝试但是无法使其工作,该函数可以工作但不适用于所有内容,如果有人可以帮助我,这将是完美的,因为我不知道如何继续这个并保存。

1 个答案:

答案 0 :(得分:0)

如果你想根据id匹配,一个简单的foreach就足够了,然后在循环期间检查它们是否有相同的密钥。考虑这个例子:

// sample data from file('db_text.txt');
$contents_from_text = array('1a34-Mark Jhonson','1a56-Jhon Smith', '1a87-Mary Walter');

// reformat
$text = array();
foreach($contents_from_text as $element) {
    list($key, $value) = explode('-', $element);
    $text[$key] = $value; 
}

$tmp = array();
// sample data from file('db_tmp.txt');
$contents_from_tmp = array('1a56-Tom Tom', '1a32-Magic Johnson', '1a23-Michael Jordan', '1a34-Larry Bird');
foreach($contents_from_tmp as $element) {
    list($key, $value) = explode('-', $element);
    $tmp[$key] = $value; 
}

// compare
foreach($tmp as $key => $value) {
    foreach($text as $index => $element) {
        if($key == $index) {
            $tmp[$key] = $element;
        }
    }
}

$contents_from_tmp = $tmp;
print_r($contents_from_tmp);

Sample Output