将JSON索引作为PHP变量访问

时间:2017-11-06 17:49:11

标签: php json

$ JSON:

{
   "https://google.com/": {
      "share": {
         "comments": 10,
         "shares": 20
      },
      "id": "https://google.com/"
   }
}

以下错误的PHP:

$url = "https://google.com/";
... json is fetched here and set as $json
$count = $json->$url->comments; 

错误:

  

PHP注意:第797行/mysite/public_html/wp-content/themes/theme/functions.php中的未定义属性:stdClass :: $ comments

我的部分修复:

$count = $json->$url->share->comments;

2 个答案:

答案 0 :(得分:0)

你必须将$url包裹在花括号中:

$count = $json->{$url}->share->comments;

答案 1 :(得分:-1)

首先尝试解码json。

$json = json_decode($json);

$url = "https://google.com/";

$count = $json->$url->share->comments;