首页 > 解决方案 > Laravel:解析 JSON 以查看

问题描述

我正在尝试显示来自此https://pomber.github.io/covid19/timeseries.json的 JSON 数据,但出现错误:

(ErrorException(code: 0): Undefined index: confirmed

我期望的是我可以显示国家名称列表以及日期、确认等。

这是我的看法:

@foreach($results as $json_d)

  {{ $json_d['date'] }}
  {{ $json_d['confirmed'] }}
  {{ $json_d['deaths'] }}
  {{ $json_d['recovered'] }}

@endforeach

这是我的控制器:

$client = new Client();

$request = $client->get('https://pomber.github.io/covid19/timeseries.json');
$response = $request->getBody()->getContents();
$results = json_decode($response, true);

return view('dashboard', compact('results'));

任何帮助,将不胜感激 :)

标签: phpjsonlaravel

解决方案


那是因为您必须将其作为nested for. 作为 Dino 的答案,但有获得国家密钥的方法。

  @foreach($results as $key => $val)
      Data for the country: {{ $key }}
    @foreach(((array)$results)[$key] as $data)
        {{ $data['date'] }}
        {{ $data['confirmed'] }}
        {{ $data['deaths'] }}
        {{ $data['recovered'] }}
    @endforeach
  @endforeach

推荐阅读