Last active
December 29, 2015 14:09
-
-
Save Trott/7681630 to your computer and use it in GitHub Desktop.
Some operations for CSV in PHP
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
<?php | |
// Here's our multiline test CSV string: | |
$csv = <<<EOD | |
2012,Camel,1 | |
2012,Marlboro,15 | |
2013,Camel,15 | |
2013,Marlboro,47 | |
total,,78 | |
EOD; | |
// Convert lines of CSV to a 2d array. | |
// Assumptions: | |
// -- No new-line characters inside any fields. | |
// -- Each line has the same number of fields. | |
function convert_csv_to_2d_array($csv) { | |
$lines = explode("\n", $csv); | |
$rv = array(); | |
foreach ($lines as $line) { | |
$rv[] = str_getcsv($line); | |
} | |
return $rv; | |
} | |
// Usage: | |
$array = convert_csv_to_2d_array($csv); | |
// Rotate 2d array 90 degrees clockwise. | |
function rotate_2d_array($array) { | |
$rv = array(); | |
foreach ($array as $rowkey => $row) { | |
foreach($row as $colkey => $col){ | |
$rv[$colkey][$rowkey]=$col; | |
} | |
} | |
return $rv; | |
} | |
// Usage: | |
$rotated_array = rotate_2d_array($array); | |
// Convert 2d array to CSV | |
function convert_2d_array_to_csv($array) { | |
$fp = fopen('php://temp', 'r+'); | |
foreach ($array as $row) { | |
fputcsv($fp, $row); | |
} | |
rewind($fp); | |
$rv = ''; | |
while ( ($line = fgets($fp)) !== false ) { | |
$rv .= $line; | |
} | |
return $rv; | |
} | |
// Usage: | |
$rotated_csv = convert_2d_array_to_csv($rotated_array); | |
echo $rotated_csv; | |
// 2012,2012,2013,2013,total | |
// Camel,Marlboro,Camel,Marlboro, | |
// 1,15,15,47,78 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment