json_decode返回array或object用法

05-28 | 夜光 | PHP笔记

PHP5.2.0及以上版本具有json_decode函数,该函数是用来解析JSON格式的数据,可以返回array(数组)或object(对象)两种结果,下面将分两种情况具体介绍json_decode的用法以及如何取得我们想要的值。

假如我们获取的JSON数据如下:(可以使用curl、fsockopen等方式获取)

{
	"from":"zh",
	"to":"en",
	"trans_result":[
		{
			"src":"\u4f60\u597d",
			"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语言中可以用以下方法取得我们想要的值:

<?php
$data = <<<STR
{
	"from":"zh",
	"to":"en",
	"trans_result":[
		{
			"src":"\u4f60\u597d",
			"dst":"Hello"
		}
	]
}
STR;
$jsondata=json_decode($data,true);
header("Content-Type: text/html; charset=UTF-8");
print_r($jsondata);
echo "<br />".$jsondata['to']; //en
echo "<br />".$jsondata['trans_result'][0]['dst']; //Hello
?>

二、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语言中可以用以下方法取得我们想要的值:

<?php
$data = <<<STR
{
	"from":"zh",
	"to":"en",
	"trans_result":[
		{
			"src":"\u4f60\u597d",
			"dst":"Hello"
		}
	]
}
STR;
$jsondata=json_decode($data);
header("Content-Type: text/html; charset=UTF-8");
print_r($jsondata);
echo "<br />".$jsondata->from; //zh
echo "<br />".$jsondata->trans_result[0]->src; //你好
?>
本文标签: ,
本文链接: json-decode-array-object/
版权所有: 玻璃泉, 转载请注明本文出处。