http://www.3lian.com/edu/2014/02-11/128395.htmlphp
1.json_decode()html
json_decodejson
(PHP 5 >= 5.2.0, PECL json >= 1.2.0)数组
json_decode — 对 JSON 格式的字符串进行编码curl
说明函数
mixed json_decode ( string $json [, bool $assoc ] )编码
接受一个 JSON 格式的字符串而且把它转换为 PHP 变量url
参数spa
json.net
待解码的 json string 格式的字符串。
assoc
当该参数为 TRUE 时,将返回 array 而非 object 。
返回值
Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.
范例
Example #1 json_decode() 的例子
代码以下 | |
<?php 上例将输出: object(stdClass)#1 (5) { array(5) {
结果为: Array ( [0] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [1] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [2] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) ) |
能够看出通过json_decode()编译出来的是对象,如今输出json_decode($data,true)试下
代码以下 | |
echo json_decode($data,true); 结果: Array ( [0] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [1] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [2] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) ) |
能够看出 json_decode($data,true)输出的一个关联数组,由此可知json_decode($data)输出的是对象,而json_decode("$arr",true)是把它强制生成PHP关联数组.
假如咱们获取的JSON数据以下:(能够使用curl、fsockopen等方式获取)
代码以下 | |
{ |
1、json_decode返回array的方式:
json_decode($data,true);用json_decode函数返回array的方式获得:
代码以下 | |
Array ) ) |
咱们在PHP语言中能够用如下方法取得咱们想要的值:
代码以下 | |
<?php |
2、json_decode返回object的方式:
json_decode($data);
用json_decode函数返回object的方式获得:
代码以下 | |
stdClass Object ) ) |
咱们在PHP语言中能够用如下方法取得咱们想要的值:
代码以下 | |
<?php STR;$jsondata=json_decode($data);header("Content-Type: text/html; charset=UTF-8");print_r($jsondata);echo "<br />".$jsondata->from; //zhecho "<br />".$jsondata->trans_result[0]->src; //你好?> |