Created
October 7, 2016 15:00
-
-
Save kadnan/e5b6b44c0f310bfb796119051a761a08 to your computer and use it in GitHub Desktop.
To Merge CSV files by Header Keys
This file contains 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
<?php | |
$files_to_read = ['file1.csv', 'file2.csv', 'file3.csv']; | |
$all = []; | |
$merged_file = []; | |
$_row = []; | |
$val = ''; | |
/** | |
* Read CSV file and return data associated with it's key | |
* @param $file_name | |
* @return array | |
*/ | |
function readCSV($file_name) | |
{ | |
$file = new SplFileObject($file_name); | |
$content = []; | |
$content_row = []; | |
$idx2 = 0; | |
$file->setFlags(SplFileObject::READ_CSV | | |
SplFileObject::SKIP_EMPTY | | |
SplFileObject::READ_AHEAD); | |
foreach ($file as $row) { | |
$new_array[] = $row; | |
} | |
for ($idx = 1; $idx < count($new_array); $idx++) { | |
$header_columns = $new_array[0]; | |
foreach ($header_columns as $header_column) { | |
$content[$header_column] = $new_array[$idx][$idx2]; | |
$idx2++; | |
} | |
$content_row[] = $content; | |
$idx2 = 0; //reset the index for new row | |
} | |
return ['columns' => $header_columns, 'data' => $content_row]; | |
} | |
$all_data = []; | |
//get combine unique columns | |
foreach ($files_to_read as $file_to_read) { | |
$file_content = readCSV($file_to_read); | |
extract($file_content); | |
$all_data[] = $data; | |
foreach ($columns as $column) { | |
if (!(in_array($column, $all))) { | |
$all[] = $column; | |
} | |
} | |
} | |
$merged_file[0] = implode(',', $all); | |
$idx_file = 0; | |
foreach ($all_data as $entry) { | |
$f = $entry; | |
foreach ($f as $item) { | |
$file1 = $item; | |
$_row = []; | |
foreach ($all as $single) { | |
$val = ($file1[$single] == null) ? "null" : $file1[$single]; | |
$_row[] = $val; | |
$val = ''; | |
} | |
$merged_file[] = implode(',',$_row); | |
$_row = []; | |
} | |
} | |
$file = new SplFileObject('merged.csv','w'); | |
foreach ($merged_file as $line) { | |
$file->fwrite($line."\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment