This article describes how to define literal objects in json data format in PHP. This is a work und. json can also be used to generate arrays in classes, for more information, see
This article describes how to define literal objects in json data format in PHP. This is a work und. json can also be used to generate arrays in classes, for more information, see
PHPer knows that PHP does not support literal terms, at least in the current version. For example, you can define an object in JS as follows:
The Code is as follows:
Var o = {'name': 'qttc ', 'url': 'www .jb51.net '};
Alert (o. name );
You can define a dictionary in Python as follows:
The Code is as follows:
O = {'name': 'qttc ', 'url': 'www .jb51.net '}
Print o ['name']
But in PHP, objects are defined as follows:
The Code is as follows:
$ A = {"name": "qttc", "url": "www.jb51.net "};
An error is reported:
The Code is as follows:
[Root @ lee www] # php a. php
PHP Parse error: syntax error, unexpected '{'in/data0/htdocs/www/a. php on line 4
We can use json format, enclose it with quotation marks, and then use json_decoude.
The Code is as follows:
$ A = '{"name": "qttc", "url": "www.jb51.net "}';
$ A = json_decode ($ );
Print_r ($ );
Execution result:
The Code is as follows:
[Root @ lee www] # php a. php
StdClass Object
(
[Name] => qttc
[Url] =>
)
Because PHP does not support literal or anonymous functions, you cannot add a function to an object when defining an object using the method defined above. You can also add an array element as follows:
The Code is as follows:
$ A = '{"name": "qttc", "url": "www.jb51.net", "arr": ["zhangsan", "lisi"]}';
$ A = json_decode ($ );
Print_r ($ );
Execution result:
The Code is as follows:
[Root @ lee www] # php a. php
StdClass Object
(
[Name] => qttc
[Url] =>
[Arr] => Array
(
[0] => zhangsan
[1] => lisi
)
)