0
我想将API调用的JSON转换为另一个Laravel网站转换为雄辩模型以将数据保存到本地Web服务器。我遇到了将主服务器请求的JSON转换为雄辩保存方法的问题。这是我现有的代码。转换Guzzle请求JSON为雄辩
public function add(Request $request)
{
// lets request the airport identifier from the central database
$client = new Client();
$res = $client->request('GET', 'http://new.fsvaos.net/api/central/airports', [
'query' => [
'icao' => $request->icao,
]
])->getBody();
// Convert the JSON to something good for Eloquent
$data = json_decode($res, true);
$airport = new Airport();
//return $data;
$airport->id = $data->id;
$airport->name = $data->name;
$airport->icao = $data->icao;
$airport->lat = $data->lat;
$airport->lng = $data->lon;
$airport->hub = 0;
$airport->fuelprice = 0;
$airport->save();
}
我究竟做错了什么?
编辑:这是从我想要添加到本地数据库的主服务器的JSON响应。
{
"id": 3682,
"name": "Hartsfield Jackson Atlanta Intl",
"city": "Atlanta",
"country": "United States",
"iata": "ATL",
"icao": "KATL",
"lat": "33.636719000000000",
"lon": "-84.428067000000000",
"alt": "1026",
"timezone": "-5.00",
"daylightsavings": "A",
"tz": "America/New_York"
}
这里也是从数组$数据
array:1 [▼
0 => array:12 [▼
"id" => 3682
"name" => "Hartsfield Jackson Atlanta Intl"
"city" => "Atlanta"
"country" => "United States"
"iata" => "ATL"
"icao" => "KATL"
"lat" => "33.636719000000000"
"lon" => "-84.428067000000000"
"alt" => "1026"
"timezone" => "-5.00"
"daylightsavings" => "A"
"tz" => "America/New_York"
]
]
如果有人想尝试一下API为自己获得JSON响应的数据转储,只是做一个GET到http://new.fsvaos.net/api/central/airports?icao=[AIRPORT ICAO]和你会得到来自世界各地的任何机场数据。
问题之一是要传递TRUE作为第二个参数json_decode说明你想要一个数组,但你引用的属性的对象。尝试将它们引用为$ data ['field']。您还需要dd()JSON响应并将其添加到您的问题。如果我们不知道JSON响应是什么样的,我们无法帮助您。 –
我刚刚编辑了OP以反映您的请求。我也尝试过做$ data ['field'],并从中得到一个未知的错误。 –