JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
csv: add version that takes assocs
authorJason Woofenden <jason@jasonwoof.com>
Wed, 11 Apr 2012 20:07:17 +0000 (16:07 -0400)
committerJason Woofenden <jason@jasonwoof.com>
Wed, 11 Apr 2012 20:07:17 +0000 (16:07 -0400)
csv.php

diff --git a/csv.php b/csv.php
index f9e311a..fd67a43 100644 (file)
--- a/csv.php
+++ b/csv.php
@@ -4,7 +4,7 @@
 # little sense, and does not actually have anything to do with commas.
 
 # pass in a 2d array (array of rows) and it'll send it to the browser
-# I can't figure out how to get multi-line fields to work, so replace newlines with 4 spaces.
+# I can't figure out how to get multi-line fields to work, so this replaces newlines with 4 spaces.
 function array2d_to_csv_download($data, $filename) {
        header('Content-type: application/csv'); 
        header('Content-Disposition: attachment; filename=' . $filename); 
@@ -22,3 +22,22 @@ function array2d_to_csv_download($data, $filename) {
        }
        exit();
 }
+
+# pass an array of associative arrays. keys from the first one will be used
+# see arary2d_to_csv_download above for more details
+function assocs_to_csv_download($data, $filename) {
+       if(count($data) < 1) {
+               $flats = array();
+       } else {
+               $flats = array(array_keys($data[0]));
+               $keys =& $flats[0];
+               foreach($data as $row) {
+                       $flat = array();
+                       foreach($keys as $k) {
+                               $flat[] = $row[$k];
+                       }
+                       $flats[] = $flat;
+               }
+       }
+       array2d_to_csv_download($flats, $filename);
+}