2016-08-13 86 views
1

我試圖從給出像這樣的響應的API獲取數據:訪問數據陣列Laravel和狂飲

{ 
    "data":[ 
     { 
     "first_name":"John", 
     "last_name":"Smith", 
     "group":"3", 
     "email":"[email protected]" 
     }, 
     { 
     "first_name":"John", 
     "last_name":"Doe", 
     "group":"3", 
     "email":"[email protected]" 
     } 
    ], 
    "meta":{ 
     "pagination":{ 
     "total":2, 
     "count":2, 
     "per_page":500, 
     "current_page":1, 
     "total_pages":1, 
     "links":[ 

     ] 
     } 
    } 
} 

我試圖用狂飲導入到我的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, 
     )); 
     } 
+0

的'$ data'變量保存JSON你教我們嗎? –

+0

是的,但我努力循環它,並將其值傳遞給模型。 –

+0

你是否運行過'json_decode',然後試着做一些像'foreach($ data ['data'] as $ item)''的東西? – Jonathon

回答

4

$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. 
} 
+0

謝謝瓦西爾 - 這正是我想念的:) –