简体   繁体   English

Php和JSON:对象(stdClass)

[英]Php and JSON : object(stdClass)

I have decoded a JSON file into a variable ( $tmp ). 我已将JSON文件解码为变量( $tmp )。 var_dump($tmp) gives: var_dump($tmp)给出:

object(stdClass)#31 (3) {
    ["c"]=> int(2)
    ["r"]=> int(2)
    ["d"]=> object(stdClass)#32 (4) {
                ["1"]=> string(2) "un"
                ["2"]=> string(4) "deux"
                ["3"]=> string(5) "trois"
                ["4"]=> string(6) "quatre"
            }
}

I want to retrieve for example "un" so I do $tmp->d["1"] but it doesn't work. 我想检索例如“un”所以我做$tmp->d["1"]但它不起作用。 I've got the following error: 我有以下错误:

Fatal error: Cannot use object of type stdClass as array in File.php on line 17

json_decode takes an additional paramater that will turn your json string into an array instead of an object json_decode采用额外的参数,将您的json字符串转换为数组而不是对象

json_decode($json_str, true)

As comment noted, your d property of your json object is an object not an array, so you can't access it with array notation (as you see there is an error) 正如注释所指出的,你的json对象的d属性是一个对象而不是一个数组,所以你不能用数组表示法访问它(你看到有一个错误)

I believe 我相信

$tmp->d->{'1'}
// "un"

should work in accessing it 应该努力访问它

php has a default function json_encode and json_decode php有一个默认函数json_encode和json_decode

$arrayOfValues = array();
$jsonString = json_encode($arrayOfValues);

and

$arrayOfValues = json_decode($jsonString);

with this function you can use variabled with json. 使用此函数,您可以使用带有json的variabled。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM