Advertisement
slovacus

convertResult

Jul 28th, 2011
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.71 KB | None | 0 0
  1. function convertResult($rs, $type, $jsonmain="") {
  2.     // receive a recordset and convert it to csv
  3.     // or to json based on "type" parameter.
  4.     $jsonArray = array();
  5.     $csvString = "";
  6.     $csvcolumns = "";
  7.     $count = 0;
  8.     while($r = mysql_fetch_row($rs)) {
  9.         for($k = 0; $k < count($r); $k++) {
  10.             $jsonArray[$count][mysql_field_name($rs, $k)] = $r[$k];
  11.             $csvString.=",\"".$r[$k]."\"";
  12.         }
  13.         if (!$csvcolumns) for($k = 0; $k < count($r); $k++) $csvcolumns.=($csvcolumns?",":"").mysql_field_name($rs, $k);
  14.         $csvString.="\n";
  15.         $count++;
  16.     }
  17.     $jsondata = "{\"$jsonmain\":".json_encode($jsonArray)."}";
  18.     $csvdata = str_replace("\n,","\n",$csvcolumns."\n".$csvString);
  19.     return ($type=="csv"?$csvdata:$jsondata);
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement