我在后端開發和 Laravel 方面還是新手。我正在使用 Laravel 8。
我想獲取一個 api 并僅訪問國家/地區資料,我無法弄清楚如何使用 foreach 或任何其他方法單獨訪問它。
這是我的提取功能:
function countries()
{
$data = Http::get('https://api.first.org/data/v1/countries');
//return json_decode($data);
return view('v_Country', ['data' => $data]);
}
如何在我的 v_Country 視圖中訪問這些資料?
提前致謝
uj5u.com熱心網友回復:
我創建了一個沙箱,您可以使用它。
我創建了一個名為的控制器CountriesController.php,其中包含與您類似的功能(只有一點錯誤保護):
public function countries() {
$countries = [];
$response = file_get_contents('https://api.first.org/data/v1/countries');
if($response !== false) {
$decodedResponse = json_decode($response, true);
if($decodedResponse !== false && isset($decodedResponse['data'])) {
$countries = $decodedResponse['data'];
}
}
return view('countries', compact('countries'));
}
然后簡單地在視圖中countries.blade.php我創建了以下 HTML 表:
<table border="1">
<tr>
<th>Code</th>
<th>Country</th>
<th>Region</th>
</tr>
@foreach ($countries as $code => $details)
<tr>
<td>{{ $code }}</td>
<td>{{ $details['country'] }}</td>
<td>{{ $details['region']}}</td>
</tr>
@endforeach
</table>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/317451.html
下一篇:如何從外鍵顯示多個值/欄位?
