Search code examples
phpfor-looparray-differencearray-intersect

Compare 2 text files and get internal id


I tried comparing 2 text files with data separated by -, in one case one file gets all data and in another case only has the data for change with the same id in this case this file it's called db_tmp.txt

The structure in both files it's this :

File txt ( the first it´s the id ) db/text.txt

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

The file for comparing, has for example the data for change, same id but different content - db_tmp.txt

1a56-Tom Tom

I created a function for comparing both files to detect if the same id and change exists:

<?php
$cron_file    = file("db_tmp.txt");
$cron_compare = file("db/test.txt");

function cron($file_temp, $file_target)
{    
    for ($fte = 0; $fte < sizeof($file_temp); $fte++) {
        $exp_id_tmp = explode("-", $file_temp[$fte]);
        $cr_temp[]  = "" . $exp_id_tmp[0] . "";
    }

    for ($ftt = 0; $ftt < sizeof($file_target); $ftt++) {
        $exp_id_targ = explode("-", $file_target[$ftt]);
        $cr_target[] = "" . $exp_id_targ[0] . "";
    }

    $diff = array_diff($cr_target, $cr_temp);

    $it = 0;
    foreach ($diff as $diff2 => $key) {
        echo $diff2;
        echo "--- $key";
        print "<br>";
    }   
}

cron($cron_file, $cron_compare);
?>

If the same id exists in tmp, i must detect the entry in the other file and change to the value of the tmp, i try but can't get this to work, the function works but not for everything, if anyone can help me, that would be perfect, because i don´t know how continue this and save.


Solution

  • If you want to match according to id, a simple foreach would suffice, then just check during the loop if they have the same key. Consider this example:

    // 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