-
-
Save armitage/032c4338c67e93cb731ff4d290cf076d to your computer and use it in GitHub Desktop.
Remap a CSV file, given the headers of the target file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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