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.