Methods of constructing JSON format and new array with PHP DataSet _php tips

Source: Internet
Author: User
I wrote a PHP result set into the JSON format function, you can call directly:

Copy Code code as follows:

function Recordtojson ($recordset)
{
$jstr = ' [';
while ($rs = $recordset->fetch ())
{
$nick = Iconv ("GBK", ' Utf-8 ', $rs [' Nick ']);/* Convert to UTF-8 encoding * *
TODO: Traverse result set
$arr _keys=array_keys ($RS);
$jstr = $jstr. ' {';
for ($i =0; $i <count ($arr _keys); $i +=2)
{
The database code is GBK and needs to convert the encoding
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;
}


The PHP default result set array has a numeric index, and the following function removes the numeric index and retains only the field index:

Copy Code code as follows:

function Rebuilderrecord ($recordset)
{
$row = 0;
while ($rs = $recordset->fetch ())
{
TODO: Traverse result set
$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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.