【问题标题】:How to acess nested json object with json_decode如何使用 json_decode 访问嵌套的 json 对象
【发布时间】:2015-12-29 21:58:23
【问题描述】:

我已经使用 php 函数 json_decode 解析了 json 格式的 api 请求

$obj = json_decode($json);

$json 是我的 json 响应。我可以轻松地回显页码

echo "Page number: ".$obj->{'data'}->{'page_number'}."</br>";

我想回显例如 imdb 代码。我试过这样但没有显示。

echo "IMDB Code: ".$obj->{'data'}->{'movies'}->{'imdb_code'}."</br>";

这是我的 json 响应

{
"status":"ok",
"status_message":"Query was successful",
"data":{
   "movie_count":1,
   "limit":1,
   "page_number":1,
   "movies":[
      {
      "id":4839,
      "url":"https:\/\/yts.ag\/movie\/the-walk-2015",
      "imdb_code":"tt3488710",
      "title":"The Walk",
      "title_english":"The Walk",
      "title_long":"The Walk (2015)",
      "slug":"the-walk-2015",
      "year":2015,
      "rating":7.6,
      "runtime":123,

有什么建议吗?

【问题讨论】:

    标签: php arrays json object


    【解决方案1】:

    在那个 json movies 是一个数组,它包含几个(?)对象,而不是对象本身, 所以你需要像这样访问它:

    echo "IMDB Code: ".$obj->{'data'}->{'movies'}[0]->{'imdb_code'}."</br>";
    

    但没有必要将属性名封装在'中:

    echo "IMDB Code: ".$obj->data->movies[0]->imdb_code."</br>";
    

    请注意,这仅通过索引0 返回/回显电影的第一个。 对于其他电影,您需要遍历该电影数组。

    【讨论】:

    • 就是这样。非常感谢:D
    • 如果这是您想要的解决方案,您可能希望接受该答案。很高兴我能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多