Home > Article > Backend Development > PHP array how to convert it to JSON or string
How to convert PHP array to JSON or string
In development, the need to convert PHP array to JSON format or string is often involved. PHP provides some built-in functions that make this conversion very simple and efficient. This article explains how to use these functions to convert a PHP array to JSON or string, and provides related code examples.
Use the json_encode()
function to easily convert a PHP array to a JSON string. This function accepts an array as argument and returns a JSON formatted string.
// 定义一个 PHP 数组 $data = array( 'name' => 'John', 'age' => 30, 'city' => 'New York' ); // 将 PHP 数组转换为 JSON 字符串 $json = json_encode($data); // 输出 JSON 字符串 echo $json;
The above code will output the following results:
{"name":"John","age":30,"city":"New York"}
Use serialize()
Function can serialize PHP arrays into strings. This function accepts an array as parameter and returns a serialized string.
// 定义一个 PHP 数组 $data = array( 'name' => 'John', 'age' => 30, 'city' => 'New York' ); // 将 PHP 数组转换为字符串 $str = serialize($data); // 输出字符串 echo $str;
The above code will output the following results:
a:3:{s:4:"name";s:4:"John";s:3:"age";i:30;s:4:"city";s:8:"New York";}
Usejson_decode()
Function can convert JSON string to PHP array. This function accepts a JSON formatted string as argument and returns a PHP array.
// 定义一个 JSON 字符串 $json = '{"name":"John","age":30,"city":"New York"}'; // 将 JSON 字符串转换为 PHP 数组 $data = json_decode($json, true); // 输出 PHP 数组 print_r($data);
The above code will output the following results:
Array ( [name] => John [age] => 30 [city] => New York )
It should be noted that the second parameter of the json_decode()
function is set to true
to ensure that JSON strings are converted to PHP associative arrays rather than objects.
Use the unserialize()
function to deserialize a string into a PHP array. This function accepts a string as parameter and returns a deserialized PHP array.
// 定义一个字符串 $str = 'a:3:{s:4:"name";s:4:"John";s:3:"age";i:30;s:4:"city";s:8:"New York";}'; // 将字符串转换为 PHP 数组 $data = unserialize($str); // 输出 PHP 数组 print_r($data);
The above code will output the following results:
Array ( [name] => John [age] => 30 [city] => New York )
The above is the basic operation and code example to convert a PHP array to JSON or string. Based on actual needs and scenarios, we can appropriately adjust and optimize these sample codes to meet specific development needs.
The above is the detailed content of PHP array how to convert it to JSON or string. For more information, please follow other related articles on the PHP Chinese website!