PHP中使用json数据格式定义字面量对象的方法_PHP

WBOY
Release: 2016-05-31 19:30:40
Original
840 people have browsed it

JSON

PHPer都知道PHP是不支持字面量了,至少目前版本都不支持。比如,在JS中可以这样定义object

代码如下:


var o = { 'name' : 'qttc' , 'url' : 'www.bitsCN.com' };
alert(o.name);


Python中定义字典,也可以这样定义:

代码如下:


o = { 'name' : 'qttc' , 'url' : 'www.bitsCN.com' }
print o['name']


但在PHP中这么定义object:

代码如下:


$a = { "name" : "qttc", "url" : "www.bitsCN.com"  };


会报错:

代码如下:


[root@lee www]# php a.php
PHP Parse error:  syntax error, unexpected '{' in /data0/htdocs/www/a.php on line 4


我们可以借用json格式,用引号把包下然后再json_decoude就好。

代码如下:


$a = '{ "name" : "qttc", "url" : "www.bitsCN.com"  }';
$a = json_decode($a);
print_r($a);


执行结果:

代码如下:


[root@lee www]# php a.php
stdClass Object
(
    [name] => qttc
    [url] => www.bitsCN.com
)


由于PHP不支持字面量or匿名函数,所以使用以上定义的方法定义object时不能添加function到object里,还可以这样添加数组元素:

代码如下:


$a = '{ "name" : "qttc", "url" : "www.bitsCN.com" , "arr":["zhangsan","lisi"] }';
$a = json_decode($a);
print_r($a);


执行结果:

代码如下:


[root@lee www]# php a.php
stdClass Object
(
    [name] => qttc
    [url] => www.bitsCN.com
    [arr] => Array
        (
            [0] => zhangsan
            [1] => lisi
        )
 
)

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