Skip to content

Instantly share code, notes, and snippets.

@ialarmedalien
Created October 15, 2014 22:39
Show Gist options
  • Save ialarmedalien/57c53fe5ad75d910eacd to your computer and use it in GitHub Desktop.
Save ialarmedalien/57c53fe5ad75d910eacd to your computer and use it in GitHub Desktop.
Remap a CSV file, given the headers of the target file
$data = array_map('str_getcsv',
['"header1","header2","header3","header4"',
'"data1","data2","data3","data4"',
'"dataA","dataB","dataC","dataD"'] );
//just get the first line of the csv1's values
$csv1 = array_shift($data);
//csv2
$data2 = array_map('str_getcsv', ['"header4","header3","header2","header1"']);
//get csv2's header values
$csv2 = array_shift($data2);
$target = [];
$acc = 0;
# set up a translation table, mapping $csv2 headers to $csv1 headers
foreach ($csv2 as $h) {
# check whether the header is in the old file headers
if (in_array($h, $csv1)) {
# if it is, find the position.
# add a reference in $target to the appropriate value in $csv1
$target[] =& $csv1[ array_search($h, $csv1) ];
}
else {
# no reference in $csv1
$target[] = '';
}
}
# sort by keys
ksort($target);
# print out the headers
echo '"' . implode('","', $target) . '"' . PHP_EOL;
$l = count($csv1);
foreach ($data as $row) {
# put the values of $row into the targeted array
for($i=0;$i<$l;$i++) {
$csv1[$i] = $row[$i];
}
echo '"' . implode('","', $target) . '"' . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment