Home  >  Article  >  Backend Development  >  How to construct JSON format and new array with PHP data set_PHP tutorial

How to construct JSON format and new array with PHP data set_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:15:08920browse

I wrote a function to convert the PHP result set into JSON format. You can call it directly:

Copy the code The code is as follows:

function RecordToJson($recordset)
{
$jstr='[';
while($rs = $recordset->Fetch())
{
//$ nick = iconv("GBK",'utf-8',$rs['nick']);/*Convert to utf-8 encoding*/
//TODO: Traverse the result set
$arr_keys=array_keys ($rs);
$jstr=$jstr.'{';
for($i=0;$i{
/ /The database encoding is gbk, the encoding needs to be converted
//TODO;iconv("GBK",'utf-8',$rs['nick']);/*Convert to utf-8 encoding*/
$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’s default result set array has a numeric index. The following function can remove the numeric index and only keep the field index:

Copy code The code is as follows:

function RebuilderRecord($recordset)
{
$row=0;
while($rs = $recordset->Fetch())
{
//TODO: Traverse the result set
$arr_keys=array_keys($rs);
for($i=0;$i{
$newrs[$row][$arr_keys[$i]]=$rs[$arr_keys[$i]];
}
$row++;
}
return $newrs;
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326137.htmlTechArticleI wrote a function to convert the PHP result set into JSON format, which can be called directly: Copy the code The code is as follows: function RecordToJson($recordset) { $jstr='['; while($rs = $recordset-Fetc...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn