0

I'm trying to show JSON data from this https://pomber.github.io/covid19/timeseries.json, but I got an error:

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

What I expect is I can show the list of Country Name following with the Date, Confirmed, etc.

Here's my view:

@foreach($results as $json_d)

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

@endforeach

And here's my controller:

$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'));

Any help would be appreciated :)

2
  • 1
    Is confirmed the only index with the warning and the others are fine? Commented Mar 19, 2020 at 19:18
  • the others as well. Commented Mar 20, 2020 at 6:29

2 Answers 2

1

That's because you have to do it as a nested for. As the answer of Dino, but there's the way of get the country key.

  @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
Sign up to request clarification or add additional context in comments.

2 Comments

I wonder is it possible to count the total 'confirmed' by country?
0

The result you get with Guzzle is a list of countries

dd($results);

gives

array:152 [▼
  "Thailand" => array:57 [▶]
  "Japan" => array:57 [▶]
  "Singapore" => array:57 [▶]
  "Nepal" => array:57 [▶]
  "Malaysia" => array:57 [▶]
  "Canada" => array:57 [▶]
  "Australia" => array:57 [▶]
  "Cambodia" => array:57 [▶]
  "Sri Lanka" => array:57 [▶]
  "Germany" => array:57 [▶]
  "Finland" => array:57 [▶]
  ...

which means you need another loop

@foreach($results as $countryData)
   @foreach($countryData as $data)
       {{ $data['date'] }}
       {{ $data['confirmed'] }}
       {{ $data['deaths'] }}
       {{ $data['recovered'] }}
   @endforeach
@endforeach

1 Comment

this is also correct! but I need to show the country name as well. thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.