1.json_decode()
json_decode
(php 5 >= 5.2.0, pecl json >= 1.2.0)
json_decode — 对 json 格式的字符串进行编码
说明
mixed json_decode ( string $json [, bool $assoc ] )
接受一个 json 格式的字符串并且把它转换为 php 变量
参数
json
待解码的 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() 的例子
代码如下 复制代码
上例将输出:
object(stdclass)#1 (5) {
[a] => int(1)
[b] => int(2)
[c] => int(3)
[d] => int(4)
[e] => int(5)
}
array(5) {
[a] => int(1)
[b] => int(2)
[c] => int(3)
[d] => int(4)
[e] => int(5)
}
$data='[{name:a1,number:123,contno:000,qqno:},{name:a1,number:123,contno:000,qqno:},{name:a1,number:123,contno:000,qqno:}]';
echo json_decode($data);
结果为:
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等方式获取)
代码如下 复制代码
{
from:zh,
to:en,
trans_result:[
{
src:u4f60u597d,
dst:hello
}
]
}
一、json_decode返回array的方式:
json_decode($data,true);用json_decode函数返回array的方式得到:
代码如下 复制代码
array
(
[from] => zh
[to] => en
[trans_result] => array
(
[0] => array
(
[src] => 你好
[dst] => hello
)
)
)
我们在php语言中可以用以下方法取得我们想要的值:
代码如下 复制代码
二、json_decode返回object的方式:
json_decode($data);
用json_decode函数返回object的方式得到:
代码如下 复制代码
stdclass object
(
[from] => zh
[to] => en
[trans_result] => array
(
[0] => stdclass object
(
[src] => 你好
[dst] => hello
)
)
)
我们在php语言中可以用以下方法取得我们想要的值:
代码如下 复制代码
from; //zh
echo
.$jsondata->trans_result[0]->src; //你好
?>