I am using PHP to query a MYSQL db to output data to a csv file.
I am currently able to query the db and export the data to the CSV file.
However i am unable to transpose the data so that the columns are rows, and rows are columns.
CODE:
function transpose($array) {
if (!is_array($array) || empty($array)) {
return array();
else {
foreach ($array as $row_key => $row) {
if (is_array($row) && !empty($row)) { //check to see if there is a second dimension
foreach ($row as $column_key => $element) {
$transposed_array[$column_key][$row_key] = $element;
else {
$transposed_array[0][$row_key] = $row;
return $transposed_array;
}
}
exportMysqlToCsv($tablename,$tokenmain, $id);
function exportMysqlToCsv($tablename,$tokenmain, $id, $filename = 'Results.csv'){
$sql_query = "select * from $tablename";
// Gets the data from the database
$result = mysql_query($sql_query);
$f = fopen('php://temp', 'wt');
$first = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first) {
fputcsv($f, array_keys($row));
$first = false;
}
fputcsv($f, $row);
} // end while
$size = ftell($f);
rewind($f);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: $size");
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
header("Content-type: text/csv");
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
fpassthru($f);
exit;
}
Somehow, those two functions should be intertwined to give me the output I need.
Any help would be greatly appreciated. thanks! -Merica