0

我已将 JSON 文件解码为变量 ( $tmp)。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"
            }
}

我想检索例如“un”,所以我这样做$tmp->d["1"]了,但它不起作用。我有以下错误:

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

2 回答 2

2

json_decode需要一个额外的参数,它将你的 json 字符串变成一个数组而不是一个对象

json_decode($json_str, true)

如评论所述,您d的 json 对象的属性是对象而不是数组,因此您无法使用数组表示法访问它(如您所见有错误)

我相信

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

应该可以访问它

于 2013-04-10T13:41:31.427 回答
0

php 有一个默认函数 json_encode 和 json_decode

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

$arrayOfValues = json_decode($jsonString);

使用此函数,您可以将变量与 json 一起使用。

于 2013-04-10T13:48:05.057 回答