John Davidson

Multidimensional loop on two CSV file php

0 comments
Message:


I need to compare two CSV file that both contain two columns: ID and URL and check if the URL are differents. The two file normally, are the same but sometimes it can change. So i have to compare if the ID is the same and if the URL has change. I would like do this with a multidimensional loop (both of files are very big). But i don't understand why at the first match, the loop is stopped.


I try to do this with a while loop:


    while ($file_odierno_fr = fgetcsv($product_dinamica_fr, 0, ";", '"')) {
while ($file_precedente_fr = fgetcsv($product_dinamica_fr_pre, 0, ";", '"' )) {
// the index [1] is the URL and ID is the index [0]
if ($file_odierno_fr[1] !== $file_precedente_fr[1] && $file_odierno_fr[0] == $file_precedente_fr[0]){
$textMail .= "\n\nURL file odierno: <b>".$file_odierno_fr[1]. "</b>\nURL file pecedente: <b>". $file_precedente_fr[1] . "</b>\n\n";
fputcsv($file,array($file_odierno_fr[1], $file_precedente_fr[1]),";");
$sendMail = TRUE;
}
}
}
fclose($product_dinamica_fr);
fclose($product_dinamica_fr_pre);

But when igo to debug this, i get juste the first match and the rest is ignored. I change some URL in the file for be sure that all is working.


I think that i can't do while loop like this, but i'm not sure. There is a way for do that with while loop?



My Answer:
",")) {
$file_odierno_it = fgetcsv($product_dinamica_it, 0, ",");

if ($file_odierno_fr[0] == $file_odierno_it[0]) {
if ($file_odierno_fr[1] != $file_odierno_it[1]) {
echo "ID: " . $file_odierno_fr[0] . " URL has changed\n";
}
}
}

This code snippet reads each line from both CSV files simultaneously and compares the ID values. If the ID values match, it checks if the URL values are different. If they are different, it prints a message indicating that the URL has changed.

If the loop is stopping after the first match, it could be due to the end of one of the files being reached before the other. You can add additional conditions to handle this scenario, such as checking if either file has reached the end before continuing the comparison:

php
while (($file_odierno_fr = fgetcsv($product_dinamica_fr, 0, ",")) !== false && ($file_odierno_it = fgetcsv($product_dinamica_it, 0, ",")) !== false) {
if ($file_odierno_fr[0] == $file_odierno_it[0]) {
if ($file_odierno_fr[1] != $file_odierno_it[1]) {
echo "ID: " . $file_odierno_fr[0] . " URL has changed\n";
}
}
}


This modification ensures that the loop continues as long as there are still lines to read from both CSV files.

Rate this post

5 of 5 based on 2006 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us