Home > Backend Development > PHP Tutorial > Understanding the two structures of JSON: object and array_php example

Understanding the two structures of JSON: object and array_php example

WBOY
Release: 2016-08-04 08:56:55
Original
1061 people have browsed it

Introduction to JSON

JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of ECMAScript. JSON uses a completely language-independent text format, but also uses conventions similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These properties make JSON an ideal data exchange language. It is easy for humans to read and write, and it is also easy for machines to parse and generate (generally used to increase network transmission rates).

Json is an extremely simple and easy-to-understand data format. The regulations about json are just as follows:

1) Parallel data are separated by commas (", ").

2) Mapping is represented by colon (": ").

3) Collections (arrays) of parallel data are represented by square brackets ("[]").

4) The mapped collection (object) is represented by curly brackets ("{}").

JSON has two structures, arrays and objects: arrays represent collections of ordered data, while objects represent collections of unordered data.

Look at the example below:

$arr = array(111,'aaa','bbb');
$arr1 = array(
'a' => 'aaa',
'b' => 222
);
$arr2 = array(
'a' => 'aaa',
'other' => array(
'bbb',1111
)
);
echo json_encode($arr); //[111,"aaa","bbb"]
echo json_encode($arr1); //{"a":"aaa","b":222}
echo json_encode($arr2); //{"a":"aaa","other":["bbb",1111]}
Copy after login

As can be seen from the above: Since javascript does not support associative arrays, json_encode() only converts the indexed array to array format, and converts the associative array to object format.

About PHP’s support for json:

json_encode only supports UTF-8 encoded data;

json_decode will always reflect only one PHP object, and the second parameter true can return an array:

$json = '{"a":"aaa","other":["bbb",1111]}';
print_r(json_decode($json));
print_r(json_decode($json, true)); 
Copy after login

The above is the understanding of objects and arrays of the two JSON structures introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank everyone for your support of the Script House website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template