使用 Laravel & Guzzle 访问 JSON 中的数据数组
access data array in JSON with 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":[
]
}
}
}
我正在尝试使用 Guzzle 导入我的 Laravel 应用程序
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'http://localhost/members.json');
$data = (string) $response->getBody();
然后一个 foreach 遍历每条记录,然后将其添加到数据库中。现在虽然我正在努力深入研究记录。
我错过了什么?
编辑:这是 foreach
foreach ($data['data'] as $person) {
Contact::create(array(
'name' => $person->first_name,
));
}
您的 $data
变量持有 json。让我们先把它做成一个漂亮的数组,然后循环遍历
$response = json_decode($data, true);
现在循环本身:
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.
}
我正在尝试从 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":[
]
}
}
}
我正在尝试使用 Guzzle 导入我的 Laravel 应用程序
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'http://localhost/members.json');
$data = (string) $response->getBody();
然后一个 foreach 遍历每条记录,然后将其添加到数据库中。现在虽然我正在努力深入研究记录。
我错过了什么?
编辑:这是 foreach
foreach ($data['data'] as $person) {
Contact::create(array(
'name' => $person->first_name,
));
}
您的 $data
变量持有 json。让我们先把它做成一个漂亮的数组,然后循环遍历
$response = json_decode($data, true);
现在循环本身:
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.
}