PHP5.2.0¼°ÒÔÉϰ汾¾ßÓÐjson_decodeº¯Êý£¬¸Ãº¯ÊýÊÇÓÃÀ´½âÎöJSON¸ñʽµÄÊý¾Ý£¬¿ÉÒÔ·µ»Øarray£¨Êý×飩»òobject£¨¶ÔÏó£©Á½ÖÖ½á¹û£¬ÏÂÃæ½«·ÖÁ½ÖÖÇé¿ö¾ßÌå½éÉÜjson_decodeµÄÓ÷¨ÒÔ¼°ÈçºÎÈ¡µÃÎÒÃÇÏëÒªµÄÖµ¡£
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() µÄÀý×Ó
´úÂëÈçÏ ¸´ÖÆ´úÂë
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
ÉÏÀý½«Êä³ö£º
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ÓïÑÔÖпÉÒÔÓÃÒÔÏ·½·¨È¡µÃÎÒÃÇÏëÒªµÄÖµ£º
´úÂëÈçÏ ¸´ÖÆ´úÂë
<?php
$data = <<<STR
{
"from":"zh",
"to":"en",
"trans_result":[
{
"src":"u4f60u597d",
"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µÄ·½Ê½µÃµ½£º
´úÂëÈçÏ ¸´ÖÆ´úÂë
¡¡