Php array to json format

Source: Internet
Author: User
Tags php array to json
This article describes how to convert a php array to a json format. The example shows how to operate arrays and json data in php, for more information about how to convert a php array to json format, see the following example. Share it with you for your reference. The specific implementation method is as follows:

The code is as follows:

Function array_to_json ($ array ){
If (! Is_array ($ array )){
Return false;
}
$ Associative = count (array_diff (array_keys ($ array), array_keys ($ array ))));
If ($ associative ){
$ Construct = array ();
Foreach ($ array as $ key => $ value ){
// We first copy each key/value pair into a staging array,
// Formatting each key and value properly as we go.
// Format the key:
If (is_numeric ($ key )){
$ Key = "key _ $ key ";
}
$ Key = "'". addslashes ($ key )."'";
// Format the value:
If (is_array ($ value )){
$ Value = array_to_json ($ value );
} Else if (! Is_numeric ($ value) | is_string ($ value )){
$ Value = "'". addslashes ($ value )."'";
}
// Add to staging array:
$ Construct [] = "$ key: $ value ";
}
// Then we collapse the staging array into the JSON form:
$ Result = "{". implode (",", $ construct )."}";
} Else {// If the array is a vector (not associative ):
$ Construct = array ();
Foreach ($ array as $ value ){
// Format the value:
If (is_array ($ value )){
$ Value = array_to_json ($ value );
} Else if (! Is_numeric ($ value) | is_string ($ value )){
$ Value = "'". addslashes ($ value )."'";
}
// Add to staging array:
$ Construct [] = $ value;
}
// Then we collapse the staging array into the JSON form:
$ Result = "[". implode (",", $ construct). "]";
}
Return $ result;
}

I hope this article will help you with php programming.

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.