Php array to json format. Php array converted to json format this article mainly introduces the method of converting php array to json format. The example shows how to operate php array and json format data, for more information, see convert php arrays to json format.
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, see
This example describes how to convert a php array to a json format. 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.
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, see...