从 REST API 检索数据
Posted
技术标签:
【中文标题】从 REST API 检索数据【英文标题】:Retrieving data from REST API 【发布时间】:2021-09-08 16:12:40 【问题描述】:我正在尝试在 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",
"round_id": 195000,
"round_name": 33,
"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,
"lost": 0,
"goals_scored": 47,
"goals_against": 2,
"points": 48
,
"away":
"games_played": 17,
"won": 12,
"draw": 5,
"lost": 0,
"goals_scored": 31,
"goals_against": 8,
"points": 41
,
"total":
"goal_difference": "68",
"points": 89
,
"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'));
【问题讨论】:
【参考方案1】:您可以返回对象而不是返回 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
【讨论】:
感谢您的回复。我按照你的方式做了,但它返回 ErrorException Undefined property: stdClass::$team_name (View: ...-app/resources/views/api.blade.php) @fsociety.updated answer.so 你可以在控制器中测试它 @fsociety.got it try $standing->team_name??null 因为很少有人没有属性 team_name 哦!现在可以了。感谢您的帮助,我花了几个小时试图找出问题所在。现在,最后一个问题,我怎样才能从排名->整体(例如 games_played)中获取数据。 $standing->overall->games_played??null以上是关于从 REST API 检索数据的主要内容,如果未能解决你的问题,请参考以下文章
Django - 使用从类似 REST 的 API 检索的数据构建报告的应用程序
如何从Google Fitness REST API检索步数数据?