In my case, my array was multidimensional, potentially with arrays as values. So I created this recursive function to completely split the array:
function array2csv($array, &$title, &$data) { foreach($array as $key => $value) { if(is_array($value)) { $title .= $key . ","; $data .= "" . ","; array2csv($value, $title, $data); } else { $title .= $key . ","; $data .= '"' . $value . '",'; } } }
Since the various levels of my array did not lend themselves to a flat CSV format, I created an empty column with the sub-array key to serve as a descriptive βentryβ to the next level of data. Output Example:
agentid fname lname empid totals sales leads dish dishnet top200_plus top120 latino base_packages G-adriana ADRIANA EUGENIA PALOMO PAIZ 886 0 19 0 0 0 0 0
You can easily remove this "intro" (descriptive) column, but in my case I repeated the column headers, i.e. inbound_leads, in each submatrix, so it gave me a break / title preceding the next section. Delete:
$title .= $key . ","; $data .= "" . ",";
after is_array () combines the code even more and removes the extra column.
Since I wanted both the header line and the data line, I pass the two variables to the function and upon completion of the function call I end both using PHP_EOL:
$title .= PHP_EOL; $data .= PHP_EOL;
Yes, I know that I leave an extra comma, but for brevity, I could not handle it here.
Jesse Q Aug 08 '14 at 3:16 2014-08-08 03:16
source share