【问题标题】:Error looping through nested Json Object Laravel遍历嵌套的 Json 对象 Laravel 时出错
【发布时间】:2019-02-02 12:42:20
【问题描述】:

我从 api 返回了 json 数据,并希望使用 Blade 输出其中的一些数据。

 9 => {#670 ▼
    +"id": 10300
    +"name": "Fallout 3: Mothership Zeta"
    +"slug": "fallout-3-mothership-zeta"
    +"url": "https://www.igdb.com/games/fallout-3-mothership-zeta"
    +"created_at": 1431649834920
    +"updated_at": 1532126985619
    +"summary": "Defy hostile alien abductors and fight your way off of the massive Mothership Zeta, orbiting Earth miles above the Capital Wasteland. Mothership Zeta takes Fall ▶"
    +"collection": 3
    +"rating": 77.763623864376
    +"popularity": 1.3333333333333
    +"total_rating": 77.763623864376
    +"total_rating_count": 29
    +"rating_count": 29
    +"game": 15
    +"games": array:10 [▶]
    +"tags": array:4 [▶]
    +"developers": array:1 [▶]
    +"publishers": array:1 [▶]
    +"category": 1
    +"player_perspectives": array:1 [▶]
    +"game_modes": array:1 [▶]
    +"themes": array:1 [▶]
    +"genres": array:2 [▶]
    +"first_release_date": 1249257600000
    +"platforms": array:3 [▶]
    +"release_dates": array:3 [▶]
    +"screenshots": array:7 [▶]
    +"cover": {#681 ▼
      +"url": "//images.igdb.com/igdb/image/upload/t_thumb/btawsi7cbgcmqlw67tpn.jpg"
      +"cloudinary_id": "btawsi7cbgcmqlw67tpn"
      +"width": 1061
      +"height": 1158
    }
  }

我希望得到的是我尝试过的封面 URL,并循环遍历所有 json 数据,返回 10 个类似上述的项目

   @foreach ($game as $games)
                  <div class="col-md-2">
                      <img src="" alt="">
                      <p>{{ $games->name}}</p>
                      @foreach ($games->cover as $cover)
                          <p>{{$cover['url']}}</p>
                      @endforeach
                  </div>
              @endforeach

目前,这是我的循环中的内容,我收到此错误

非法字符串偏移'url'

【问题讨论】:

  • 我可以看到这是一个更大的数组的第 10 个元素,$arr[9]。您是尝试仅访问这个还是打算访问数组的其他元素?
  • 只有这个以及名字和ID
  • 执行此操作时遇到哪个错误?或者,如果没有错误,会发生什么?
  • 未定义属性:stdClass::$cover 我遇到的错误

标签: json laravel laravel-blade


【解决方案1】:

试试这个:

{{ $arr[9]->id }}
{{ $arr[9]->name }}
{{ $arr[9]->cover->url }}

注意,我假设这是第 10 个元素的较大数组的名称是 $arr。将该名称替换为代码中的名称。

【讨论】:

  • 但是我为每个循环做一个循环并循环遍历每个循环,
  • 所以如果我只想得到一个,这很好,但循环遍历所有 10 个对象是个问题
【解决方案2】:

在您的循环中,将$games 更改为$game

@foreach($games as $game)
    <div class="col-md-2">
        <img src="" alt="">
        <p>{{$game->name}}</p>
        <p>{{$game->cover->url}}</p> 
    </div>
@endforeach

【讨论】:

    猜你喜欢
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    相关资源
    最近更新 更多