Page 1 of 1

Compare 2 csv files and highlight row on match

Posted: Mon Apr 13, 2020 5:36 am
by johanvena
I have following working code to compare 2 csv files - base.csv file to compare to master.csv file using function row_compare. For now I am echoing the master.csv file followed by echoing the match items. I need help to echo only the master.csv file in a table format and highlight the rows that match the base.csv files items.

Code: Select all

function row_compare($a, $b)
{
    if ($a === $b) {
        return 0;
    }

    return (implode("",$a) < implode("",$b) ) ? -1 : 1;
}

$file1 = new SplFileObject("master.csv");
$file1->setFlags(SplFileObject::READ_CSV);

$file2 = new SplFileObject("../../base.csv");
$file2->setFlags(SplFileObject::READ_CSV);

foreach ($file1 as $row) {
    $csv_1[] = $row;
}

foreach ($file2 as $row) {
    $csv_2[] = $row;
}

$unique_to_csv1 = array_udiff($csv_1, $csv_2, 'row_compare');
$unique_to_csv2 = array_udiff($csv_2, $csv_1, 'row_compare');

$all_unique_rows = array_merge($unique_to_csv1,$unique_to_csv2);

foreach($all_unique_rows as $unique_row) {
    foreach($unique_row as $element) {
        echo $element . "   ";
    }
    echo '<br />';
}