這應該工作:
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;
});
如果他想以某種方式操縱結果集,該怎麼辦? – NullUserException 2010-08-07 13:00:23
塞巴斯蒂安的解決方案似乎工作 – 2010-08-07 13:09:22
@NullUserException他不應該使用這個泛型然後。 – 2010-08-07 13:15:49