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 ...