In PHP programming, JSON format data is often used, and converting JSON arrays to strings is a common problem. Below we will introduce how to convert JSON array to string in PHP.
PHP provides a very convenient function json_encode()
, which can convert a PHP array into a JSON format string. However, when the PHP array contains multi-dimensional arrays, the json_encode()
function cannot satisfy us. Therefore, we need to use a homemade function.
The following is a function that converts a JSON array to a string:
function json_arr2string($arr, $indent=0){ $str = ""; $indstr = ""; for ($i=0; $i<$indent; $i++){ $indstr .= " "; } foreach ($arr as $key => $val){ if (is_array($val)){ $str .= $indstr . '"' . $key . '": {' . "\n" . json_arr2string($val, $indent+1) . $indstr . "},\n"; } else{ $str .= $indstr . '"' . $key . '": "' . $val . '",' . "\n"; } } return "{" . "\n" . substr($str, 0, -2) . "\n" . $indstr . "}"; }
The function has two parameters. The first parameter $arr
is the JSON array to be converted to a string. The second parameter has a default value of 0 and is used to process multi-dimensional arrays. The
function first creates an empty string variable $str
and a string variable used for indentation $indstr
, and then checks each element in the array. Process multidimensional arrays by calling itself recursively until all elements have been processed.
Finally, delete the last two characters of the string variable $str
(that is, delete the last comma and the spaces adjacent to it), and add curly braces and newlines to return the final String.
The following is an example that demonstrates how to use the above function to convert a JSON array containing a multidimensional array into a string:
$json_arr = array( "name" => "PHP", "version" => "7.3.5", "extension" => array( "json" => "enabled", "curl" => "enabled", "pdo" => "enabled" ), "framework" => array( "name" => "Laravel", "version" => "5.8.18" ) ); $json_str = json_arr2string($json_arr); echo $json_str;
The above code will output the following result:
{ "name": "PHP", "version": "7.3.5", "extension": { "json": "enabled", "curl": "enabled", "pdo": "enabled" }, "framework": { "name": "Laravel", "version": "5.8.18" } }
This Is a string conforming to JSON format, which converts the original JSON array into a string.
Summary: Using the above self-made function json_arr2string()
can easily convert JSON arrays containing multi-dimensional arrays into strings. If you have not encountered multi-dimensional arrays in PHP programming, the json_encode()
function is sufficient.
The above is the detailed content of How to convert JSON array to string in php. For more information, please follow other related articles on the PHP Chinese website!