tags:

views:

233

answers:

2

I have two csv file.

First File has

date offerid clicks orders

Second File has

date offerid shown

How can I merge this two csv file programmatically in php ?

A: 

Read both of those files into arrays in PHP.

Then, do a nested loop

for (all items in array A) {
  find a matching item in array B
  set properties from item from array B on the item in array A
}

As a result, you'll have an array A that has information from both CSV files.

Alex
Can you provide a sample code to see how it would work.
Rachel
A: 
class DataRow extends Object {
    var $date;
    var $offerid;
    var $clicks;
    var $orders;
    var $shown;
}

function getMatchingRow($date, $offerid, $rows){
    foreach($rows as $myRow){
        if($myRow->date == $date && $myRow->offerid == $offerid){
            return $myRow;
        }
    }
    return null;
}

$rows = array();
$complete_rows = array();

$first = file('FirstFile.csv');
$second = file('SecondFile.csv');

foreach($first as $line){
    $row = new DataRow();
    $parts = explode(',',$line);
    $row->date = $parts[0];
    $row->offerid = $parts[1];
    $row->clicks = $parts[2];
    $row->orders = $parts[3];
    $rows[] = $row;
}

foreach($second as $line){
    $parts = explode(',',$line);
    $row = getMatchingRow($parts[0],$parts[1],$rows);
    if(!is_null($row){
        $row->shown = parts[2];
    } 
    $complete_rows[] = $row;
}

// loop over $completed_rows and write each to a new file

Untested, but that should get you most of the way there. Good luck.

inkedmn
Exploding ona "," isn't enough to parse a csv file. If any of the data has a "," in it, you're screwed.
Alan Storm