For developers, PHP is a very convenient programming language. In the development of web applications, PHP arrays and JSON arrays are very commonly used data structures. Here, we will delve into how to convert an array into a JSON formatted array in PHP.
PHP 5.2.0 and above supports using thejson_encode()
function to convert PHP arrays into JSON format, and also provides some optional parameters to adjust the behavior of JSON arrays.
The following is a simple PHP array:
$php_array = array( 'fruit' => 'apple', 'number' => 10, 'price' => 2.5 );
This PHP array can be converted to JSON format using thejson_encode()
function:
$json_array = json_encode($php_array);
The above code Convert$php_array
to JSON format and assign it to the$json_array
variable. Now,$json_array
saves the following JSON string:
{"fruit":"apple","number":10,"price":2.5}
We can use thejson_decode()
function to convert it back:
$decoded = json_decode($json_array);
Now , we can access the elements of the original PHP array using$decoded
variables:
echo $decoded->fruit; // 输出 "apple" echo $decoded->number; // 输出 10 echo $decoded->price; // 输出 2.5
Use optional parameters to change the behavior of the JSON array:
After usingjson_encode( )
function, we can also pass some optional parameters to change the behavior of the JSON array.
JSON_PRETTY_PRINT
: Used to format a JSON array to make it easier to read. Here is the JSON string generated after applying this option:{ "fruit": "apple", "number": 10, "price": 2.5 }
JSON_FORCE_OBJECT
: Cast a PHP array to an object.$php_array = array('apple', 'banana', 'orange'); $json_array = json_encode($php_array, JSON_FORCE_OBJECT); //生成json数组, //{ // "0": "apple", // "1": "banana", // "2": "orange" //}
JSON_UNESCAPED_UNICODE
: Causes the generated JSON array to not be UTF-8 encoded.$php_array = array('西瓜', '西红柿', '黄瓜'); $json_array = json_encode($php_array, JSON_UNESCAPED_UNICODE); // 生成的 JSON 字符串:["西瓜","西红柿","黄瓜"]
Summary:
It is very simple to use thejson_encode()
function to convert a PHP array into a JSON format array. When retrieving a PHP array from a JSON formatted array, we can use thejson_decode()
function. You can also use options to change the behavior of JSON arrays to meet specific needs.
The above is the detailed content of Convert php array to json array. For more information, please follow other related articles on the PHP Chinese website!