PHP array into JSON format method, PHP array json format _php tutorial

Source: Internet
Author: User
Tags php array to json

PHP array to JSON format method, PHP array JSON format


The example in this article describes how the PHP array is converted to JSON format. Share to everyone for your reference. The implementation method is as follows:

Copy CodeThe 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_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 is helpful to everyone's PHP programming.

http://www.bkjia.com/PHPjc/965352.html www.bkjia.com true http://www.bkjia.com/PHPjc/965352.html techarticle PHP array into JSON format method, PHP array JSON format This article describes the PHP array into JSON format method. Share to everyone for your reference. The implementation method is as follows: Copy ...

  • Related Article

    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.