PHP dataset construction of JSON format and new array method

Source: Internet
Author: User
You can directly call a function that converts a PHP result set to JSON format. if you need a PHP result set, you can refer to the function that converts it to JSON format, you can directly call:

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: traverses the result set.
$ Arr_keys = array_keys ($ rs );
$ Jstr = $ jstr .'{';
For ($ I = 0; $ I
{
// The database encoding is gbk and 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;
}



The default result set of PHP has a numeric index. the following function can remove the numeric index and only retain the field index:

The code is as follows:


Function RebuilderRecord ($ recordset)
{
$ Row = 0;
While ($ rs = $ recordset-> Fetch ())
{
// TODO: traverses the result set.
$ Arr_keys = array_keys ($ rs );
For ($ I = 0; $ I
{
$ 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.