微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 REST API 检索数据

如何解决从 REST API 检索数据

我正在尝试在 Laravel 中实现我的第一个项目,该项目将包含 API,更具体地说是 Sportmonks API。获取数据并将其显示在我的视图中的最佳方法是什么?

我已经设法显示了一些数据,但我不知道从“排名”以及其中包含的表格(总体、主场、客场、总数)中显示数据的正确方法)

API 返回

{
    "data": [{
        "id": 77447501,"name": "1st Phase","league_id": 501,"season_id": 17141,"round_id": 195000,"round_name": 33,"type": "Group Stage","stage_id": 77447501,"stage_name": "1st Phase","resource": "stage","standings": {
            "data": [{
                "position": 1,"team_id": 62,"team_name": "Rangers","group_id": null,"group_name": null,"overall": {
                    "games_played": 33,"won": 28,"draw": 5,"lost": 0,"goals_scored": 78,"goals_against": 10,"points": 89
                },"home": {
                    "games_played": 16,"won": 16,"draw": 0,"goals_scored": 47,"goals_against": 2,"points": 48
                },"away": {
                    "games_played": 17,"won": 12,"goals_scored": 31,"goals_against": 8,"points": 41
                },"total": {
                    "goal_difference": "68","result": "Championship Round","points": 89,"recent_form": "WWWWD","status": null
            }],....
        }
    }]
}         

控制器

public function index() {
    $response = Http::get('apiurl');
    $response->json();
    $result = json_decode($response,true);
    $matches = $result['data'];
    return view('/api',compact('matches'));
}

解决方法

你可以返回对象而不是返回 json

$response = Http::get('apiurl');
$result=$response->object();
$matches=$result->data;

return view('/api',compact('matches'));

然后在你看来

@foreach($matches as $match)
 
  @foeach($match->standings->data as $standing)

   {{$standing->team_name??null}}

  @endforeach
 
@endforeach

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。