自己写了个PHP结果集转换成JSON格式的函数,可以直接调用:
function RecordToJson(
$recordset)
{
$jstr='[';
while( $rs = $recordset->Fetch())
{
// $nick = iconv("GBK",'utf-8',$rs['nick']);/*转换为utf-8编码*/
//TODO:遍历结果集
$arr_keys= array_keys( $rs);
$jstr= $jstr.'{';
for( $i=0; $i< count( $arr_keys); $i+=2)
{
// 数据库编码为gbk,需要转换编码
//TODO;iconv("GBK",'utf-8',$rs['nick']);/*转换为utf-8编码*/
$key= iconv("GBK",'utf-8', $arr_keys[ $i]); // $arr_keys[$i];
$value= iconv("GBK",'utf-8', $rs[ $arr_keys[ $i]]); // $rs[$arr_keys[$i]];
$jstr= $jstr.'"'. $key.'":"'. $value.'",';
}
$jstr= substr( $jstr,0, strlen( $jstr)-1);
$jstr= $jstr.'},';
}
$jstr= substr( $jstr,0, strlen( $jstr)-1);
$jstr= $jstr.']';
return $jstr;
}
{
$jstr='[';
while( $rs = $recordset->Fetch())
{
// $nick = iconv("GBK",'utf-8',$rs['nick']);/*转换为utf-8编码*/
//TODO:遍历结果集
$arr_keys= array_keys( $rs);
$jstr= $jstr.'{';
for( $i=0; $i< count( $arr_keys); $i+=2)
{
// 数据库编码为gbk,需要转换编码
//TODO;iconv("GBK",'utf-8',$rs['nick']);/*转换为utf-8编码*/
$key= iconv("GBK",'utf-8', $arr_keys[ $i]); // $arr_keys[$i];
$value= iconv("GBK",'utf-8', $rs[ $arr_keys[ $i]]); // $rs[$arr_keys[$i]];
$jstr= $jstr.'"'. $key.'":"'. $value.'",';
}
$jstr= substr( $jstr,0, strlen( $jstr)-1);
$jstr= $jstr.'},';
}
$jstr= substr( $jstr,0, strlen( $jstr)-1);
$jstr= $jstr.']';
return $jstr;
}
PHP默认的结果集数组有数字索引,下面函数可以去除数字索引,只保留字段索引:
function RebuilderRecord(
$recordset)
{
$row=0;
while( $rs = $recordset->Fetch())
{
// TODO:遍历结果集
$arr_keys= array_keys( $rs);
for( $i=0; $i< count( $arr_keys); $i+=2)
{
$newrs[ $row][ $arr_keys[ $i]]= $rs[ $arr_keys[ $i]];
}
$row++;
}
return $newrs;
}
{
$row=0;
while( $rs = $recordset->Fetch())
{
// TODO:遍历结果集
$arr_keys= array_keys( $rs);
for( $i=0; $i< count( $arr_keys); $i+=2)
{
$newrs[ $row][ $arr_keys[ $i]]= $rs[ $arr_keys[ $i]];
}
$row++;
}
return $newrs;
}