根據PHP的手冊,json_decode以適當的PHP類型返回以JSON編碼的值。值true,false和null分別作爲TRUE,FALSE和NULL返回。如果JSON無法解碼或編碼數據比遞歸限制更深,則返回NULL。
<?php
$json_output = '[{ "title": "red" }, { "title": "blue" }, { "title": "yellow" }]';
$mydata = json_decode($json_output);
var_dump($mydata);
/* Output:
array(3) {
[0]=>
object(stdClass)#1 (1) {
["title"]=>
string(3) "red"
}
[1]=>
object(stdClass)#2 (1) {
["title"]=>
string(4) "blue"
}
[2]=>
object(stdClass)#3 (1) {
["title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]->title;
// Output: red
?>
當第二個參數爲TRUE時,返回的對象將被轉換爲關聯數組。
<?php
$json_output = '[{ "title": "red" }, { "title": "blue" }, { "title": "yellow" }]';
$mydata = json_decode($json_output, TRUE);
var_dump($mydata);
/* Ouput:
array(3) {
[0]=>
array(1) {
["title"]=>
string(3) "red"
}
[1]=>
array(1) {
["title"]=>
string(4) "blue"
}
[2]=>
array(1) {
["title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]['title'];
// Output: red
?>
在一個側面說明,訪問包含下PHP的命名約定不允許任何人物的對象內的元件可以通過用大括號包裹所述索引來完成。
<?php
$json_output = '[{ "h1-title": "red" }, { "h1-title": "blue" }, { "h1-title": "yellow" }]';
$mydata = json_decode($json_output);
var_dump($mydata);
/* Output:
array(3) {
[0]=>
object(stdClass)#1 (1) {
["h1-title"]=>
string(3) "red"
}
[1]=>
object(stdClass)#2 (1) {
["h1-title"]=>
string(4) "blue"
}
[2]=>
object(stdClass)#3 (1) {
["h1-title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]->{'h1-title'};
// Output: red
?>
'var_dump($ mydata)'你看到了什麼? –
'json_decode($ json_output,true)' - >'$ mydata [1] ['title'] // blue' – Xorifelse
@Xorifelse它的索引爲'0'。 OP錯誤地使用索引'1'來獲取明顯錯誤的第一個條目 – rbr94