php将mysql转换为json字符串_在PHP中将MySQL记录集转换为JSON字符串

小编典典

这应该工作:

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;

});

2020-07-27

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值