Jump to content

Recommended Posts

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!

 

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.

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 by Psycho
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.