Skip to content

Instantly share code, notes, and snippets.

@forsvunnet
Forked from yratof/csv-merge.php
Created January 20, 2015 22:24
Embed
What would you like to do?
<?php /* This changes the CSV into another CSV. But merges duplicated fields. */
$fh = fopen("clubexp.csv", "r");
$row = 0;
$clubs = array();
while (($data = fgetcsv($fh, 1000, ",")) !== FALSE) {
// ID
$club_id = $data[0];
// Day
$day = $data[17];
// Times
$start = $data[18];
$end = $data[19];
// Type of Group
$type = $data[16] ? $data[16] .' - ' : '';
// Format the date
$date_line = $type . $day .': '. $start .' - '. $end;
unset( $data[16] );
unset( $data[18] );
unset( $data[19] );
$data = array_values( $data );
if ( array_key_exists($club_id, $clubs) ) {
$clubs[$club_id][16] .= "\n". $date_line;
} else {
$data[16] = $date_line;
$clubs[$club_id] = $data;
}
$row++;
}
if (count($row) > 0) {
$fh = fopen('clubexp_merged.CSV', 'w');
if (!$fh) throw new Exception("Can't open CSV file for merged data");
foreach($clubs as $club_id => $vals) {
array_unshift($vals, $club_id);
if (!fputcsv($fh, $vals)) throw new Exception("Can't write data to merged CSV file");
}
fclose($fh);
}
echo '<pre>';
print_r( $clubs );
echo '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment