在PHP中将MySQL记录集转换为JSON字符串

TMP*_*guy 6 php mysql json

PHP中是否有函数或类可以传递MySQL记录集,并且我返回一个JSON字符串,可以传递回Ajax请求中的JavaScript函数?

这样的事情:

function recordSetToJson($recordset) {
 while($rs1 = mysql_fetch_row($recordset)) {
  for($count = 0; $count < count($rs1); $count++) {
   //  read and add field to JSON
  }
  $count++;
 }

 return $jasonstring
}
Run Code Online (Sandbox Code Playgroud)

Seb*_*oli 13

这应该工作:

function recordSetToJson($mysql_result) {
 $rs = array();
 while($rs[] = mysql_fetch_assoc($mysql_result)) {
    // you don´t really need to do anything here.
  }
 return json_encode($rs);
}
Run Code Online (Sandbox Code Playgroud)

如果您需要处理结果集,你可以使用下面的 - 更复的版本,可以让你添加一个回调函数,将在每一个记录被调用,必须返回已经处理过该记录:

function recordSetToJson($mysql_result, $processing_function = null) {
 $rs = array();
 while($record = mysql_fetch_assoc($mysql_result)) {
   if(is_callable($processing_function)){
    // callback function received.  Pass the record through it.
    $processed = $processing_function($record);
    // if null was returned, skip that record from the json.
    if(!is_null($processed)) $rs[] = $processed;
   } else {
    // no callback function, use the record as is.
    $rs[] = $record;
   }
 }
 return json_encode($rs);
}
Run Code Online (Sandbox Code Playgroud)

像这样用它:

$json = recordSetToJson($results, 
    function($record){ 
      // some change you want to make to every record:
      $record["username"] = strtoupper($record["username"]);
      return $record;
    });
Run Code Online (Sandbox Code Playgroud)


Nul*_*ion 5

PHP中是否有函数或类可以传递MySQL记录集,并且我返回一个JSON字符串,可以传递回Ajax请求中的JavaScript函数?

是: json_encode()