如果您访问任何用户https://api.github.com/users/{USERNAME}/repos
的github api,您将找到该用户列出的所有存储库,现在我想在我的刀片中循环这个存储库,但我不能。
我尝试过上面分享的简单网址,以及json_decode
,但没有运气。
知道如何循环这样的数据吗?
如果您使用Guzzle来调用API(我无法评论清晰度),您可以像这样获得调用的结果(其中$ response是您的调用值):
$response = json_decode($response->getBody()->getContents());
然后传递给视图:
return view('view')->with(compact('response'));
然后用刀片循环:
@foreach ($response as $results)
// do something
@endforeach
如果对象不是您想要使用的对象,可以通过将true
的第二个参数传递给json_decode()
函数将这些结果转换为数组
希望有帮助,但如果不是让我知道:)
如果您的申请中没有Guzzle:
1 - 使用Composer将依赖项拉入应用程序
composer require guzzlehttp/guzzle
2 - 在控制器中实例化Guzzle,它将调用Github API并发出GET
请求:
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/users/{USERNAME}/repos');
3 - 访问结果:
$response = json_decode($response->getBody()->getContents());
来自Guzzle Docs的信息:http://docs.guzzlephp.org/en/stable/
我正在使用此代码,现在没有问题
// We make the actuall curl initialization
$ch = curl_init(MY_REPOS_API_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// We set the right headers: any user agent type, and then the custom token header part that we generated
curl_setopt($ch, CURLOPT_HTTPHEADER, array('User-Agent: Awesome-Octocat-App'));
// We execute the curl
$output = curl_exec($ch);
// And we make sure we close the curl
curl_close($ch);
// Then we decode the output and we could do whatever we want with it
$output = json_decode($output);