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 }
这应该工作:
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); }
如果需要处理结果集,则可以使用以下更复杂的版本,该版本可让您添加将在每条记录上调用的回调函数,并且必须返回已处理的记录:
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; });