PHP中Json应用

导语:Json全称是JavaScript Object Notation,本来是JavaScript对象的一种表示和描述方式。现在已经和XML一样,成为了一种通用的数据传输格式,且由其更加轻量级,得到了广泛的使用。让我们了解一下其应用方法吧!

PHP中Json应用

在PHP中,与Json直接相关的两个常用函数是json_encode和json_decode,json_encode即将PHP实体(数组或对象等类型)进行接送编码,转换成Json字符串(文本)格式,以便进行数据传输。另一方面,json_decode是对Json字符串进行解码,得到原来的PHP实体。在PHP中,经常使用的就是对对象和数组进行Json传输。

当对一维数组和对象进行json_decode时,会转化后的'Json字符串发现其形式一样。

如下代码所示:

1 <?php

2 $people1 = array('name'=>'qqyumidi', 'age'=>'24');

3 $people1_json = json_encode($people1);

4 echo $people1_json;

5 echo "<br/>";

6

7 class People{

8 public $name;

9 public $age;

10

11 public function __construct($name, $age){

12 $this->name = $name;

13 $this->age = $age;

14 }

15 }

16

17 $people2 = new People('qqyumidi', '24');

18 $people2_json = json_encode($people2);

19 echo $people2_json;

转化后的Json字符串格式都为:{"name":"qqyumidi","age":"24"}

如果现在有此Json字符串,需要对其进行还原成原来格式,怎么办呢,到底是解析成对象还是数组形式呢,幸好,json_decode函数中为了对此进行区分,提供了第二个可选布尔型参数,如果第二个参数为true,则解析为数组,否则解析成对象。且默认是false。这也正是json_decode函数第二个参数的来由。

1 $json_str = '{"name":"qqyumidi","age":"24"}';

2 $result1 = json_decode($json_str);

3 $result2 = json_decode($json_str, true);

4 print_r($result1);

5 echo "<br/>";

6 print_r($result2);

可以看到输出结果为:

stdClass Object ( [name] => qqyumidi [age] => 24 )

Array ( [name] => qqyumidi [age] => 24 )