Ste*_*ant 2 php import json laravel guzzle
我正在尝试从提供如下响应的 API 中检索数据:
{
"data":[
{
"first_name":"John",
"last_name":"Smith",
"group":"3",
"email":"jsmith@talktalk.net"
},
{
"first_name":"John",
"last_name":"Doe",
"group":"3",
"email":"johndoe@aol.com"
}
],
"meta":{
"pagination":{
"total":2,
"count":2,
"per_page":500,
"current_page":1,
"total_pages":1,
"links":[
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用 Guzzle 导入到我的 Laravel 应用程序中
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'http://localhost/members.json');
$data = (string) $response->getBody();
Run Code Online (Sandbox Code Playgroud)
然后 foreach 循环遍历每条记录,然后将其添加到数据库中。现在虽然我正在努力钻研记录。
我错过了什么?
编辑:这是foreach
foreach ($data['data'] as $person) {
Contact::create(array(
'name' => $person->first_name,
));
}
Run Code Online (Sandbox Code Playgroud)
您的$data变量包含 json。让我们先让它成为一个漂亮的数组,然后循环它
$response = json_decode($data, true);
Run Code Online (Sandbox Code Playgroud)
现在循环本身:
foreach($response['data'] as $element) {
$firstName = $element['first_name'];
$lastName = $element['last_name'];
$group = $element['group'];
$email = $element['email'];
//Now here you can send it to the modele and create your db row.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3342 次 |
| 最近记录: |