ndzynes Posted May 6, 2014 Share Posted May 6, 2014 Hi, I have a list of products in CSV format, but I need to following to take place: I need PHP to read CSV file and compare it with a previous CSV file For product additions, generate a new CSV file with just new items called "Additions.CSV" For product deletions, generate a new CSV file with just deleted products called "Deleted.CSV" Any guidance would be appreciated. Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/288293-track-changes-in-csv-and-generate-new-files/ Share on other sites More sharing options...
ginerjm Posted May 6, 2014 Share Posted May 6, 2014 Assuming that the layout of the csv files is constant, what's the problem? Open up the new and the old file; read a line from each and compare them. Or - if the file order can't be guaranteed - read the records and store them each in an array using the product id (or something) as the array index. Then loop thru the old one and try and find the same record in the new one and handle it. Quote Link to comment https://forums.phpfreaks.com/topic/288293-track-changes-in-csv-and-generate-new-files/#findComment-1478478 Share on other sites More sharing options...
Psycho Posted May 6, 2014 Share Posted May 6, 2014 (edited) Read the two files into separate arrays. I assume each product has something such as a unique ID along with additional data about the product (name, description, etc). Use the unique identifier as the index for each array element and then make each element a subarray with all the other data E.g. $newCSV = array( '1' => array('name' => 'Prod 1', 'Desc' => 'Description for product 1'), '4' => array('name' => 'Prod 4', 'Desc' => 'Description for product 4'), '7' => array('name' => 'Prod 7', 'Desc' => 'Description for product 7') ) Once you have the two arrays $newCSV and $currentCSV (or whatever you want to name them) you can use the function array_diff_key() to determine the new records and the deleted keys - just depends on the order of the parameters $deletions = array_diff_key($currentCSV, $newCSV); $additions = array_diff_key($newCSV, $currentCSV); Then loop thru the old one and try and find the same record in the new one and handle it. Look ma - no loops! Edited May 6, 2014 by Psycho Quote Link to comment https://forums.phpfreaks.com/topic/288293-track-changes-in-csv-and-generate-new-files/#findComment-1478484 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.