【发布时间】:2016-12-04 21:44:14
【问题描述】:
我正在尝试将来自 API 调用的 JSON 转换为另一个 Laravel 网站到一个雄辩的模型,以将数据保存到本地 Web 服务器。我在将从主服务器请求的 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"
}
这也是数组 $data 中的数据转储
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=[AIRPORTICAO],您将获得来自世界各地的任何机场数据。
【问题讨论】:
-
其中一个问题是您将 TRUE 作为第二个参数传递给 json_decode,表示您需要一个数组,但您将属性作为对象引用。尝试将它们引用为 $data['field']。您还需要 dd() JSON 响应并将其添加到您的问题中。如果我们不知道 JSON 响应是什么样的,我们将无法帮助您。
-
我刚刚编辑了 OP 以反映您的要求。我也尝试过 $data['field'] ,但这样做时出现未知错误。
标签: php json laravel eloquent guzzle