在PHP中将MySQL记录集转换为JSON字符串 [英] Convert MySQL record set to JSON string in PHP

查看:95
本文介绍了在PHP中将MySQL记录集转换为JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中是否存在可以传递MySQL记录集并返回可以在Ajax请求中传递回JavaScript函数的JSON字符串的函数或类?

Is there a function or class in PHP that I can pass a MySQL recordset and I get a JSON string returned that can be passed back to a JavaScript function in an Ajax request?

类似这样的东西:

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
}

推荐答案

这应该有效:

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);
}

如果需要处理结果集,则可以使用以下更复杂的版本,该版本允许您添加将在每条记录上调用的回调函数,并且必须返回已处理的记录:

If you need to manipulate the result set you can use the following -more complex- version that lets you add a callback function that will be called on every record and must return that record already processed:

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);
}

像这样使用它:

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

这篇关于在PHP中将MySQL记录集转换为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆