Home > Article > Backend Development > What are the differences and connections between PHP arrays and JSON objects?
The key difference between PHP arrays and JSON objects is that the data structures are different. Arrays are associative arrays, and the keys can be strings or numbers; while JSON objects are a collection of key-value pairs, and the keys must be strings. The representation is different, arrays are represented by square brackets [], and JSON objects are represented by curly brackets {}. The data types are different, array elements can be of any type, and JSON object values must be of a specific type. The operation methods are different, arrays use PHP array functions, and JSON objects use json_encode() and json_decode() functions.
Similarities and differences between PHP arrays and JSON objects
Differences
[]
square brackets, while JSON objects are represented by {}
curly brackets. json_encode()
and json_decode()
functions. decoding. Contact
json_encode()
to convert a PHP array to a JSON object, and json_decode()
to convert a JSON object Convert to PHP array. Practical case
Convert PHP array to JSON object:
$array = ["name" => "John", "age" => 30]; $json = json_encode($array); echo $json; // 输出:{"name":"John","age":30}
Convert JSON object Convert to PHP array:
$json = '{ "name": "John", "age": 30 }'; $array = json_decode($json, true); print_r($array); // 输出:Array ( [name] => John [age] => 30 )
The above is the detailed content of What are the differences and connections between PHP arrays and JSON objects?. For more information, please follow other related articles on the PHP Chinese website!