0

I'm trying to count integer value from JSON: https://pomber.github.io/covid19/timeseries.json but I got 1 for each key. What I expect is to count the total 'confirmed' from all countries by date as a key.

Here's my controller:

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

$confirmed_array = array();

if ( ! empty( $posts_dates ) ) {
    foreach ( $posts_dates as $key => $val ) { 
        foreach ( ((array)$posts_dates)[$key] as $data ) {
            $date_confirmed = new \DateTime( $data['date'] );
            $day = $date_confirmed->format( 'd M y' );
            $confirmed = count((array)$data['confirmed']);
            $confirmed_array [ $day ] = $confirmed;
        }

    } 
}
return $confirmed_array;

Here's the result:

{
"22 Jan 20": 1,
"23 Jan 20": 1,
"24 Jan 20": 1,
"25 Jan 20": 1,
"26 Jan 20": 1,
"27 Jan 20": 1,
"28 Jan 20": 1,
"29 Jan 20": 1,
"30 Jan 20": 1,
"31 Jan 20": 1,
....
}

UPDATE

I want to get the output to looks like below:

{
  "date": [
     "22 Jan 20",
     "23 Jan 20",
     "24 Jan 20",
     "25 Jan 20",
     .....
   ],
  "total_confirmed": [
     555,
     653,
     941,
     1434,
     .....
   ],
   "max_value_of_total_confirmed": 12214
}

Any help would be appreciated :)

1 Answer 1

1

This code just loops through each countries data and then for each date it adds the data to the result array...

foreach ( $posts_dates as $country => $data )   {
    foreach ( $data as $date => $dateData )    {
        if ( !isset($confirmed_array[$dateData['date']]) )  {
            $confirmed_array[$dateData['date']] = 0;
        }
        $confirmed_array[$dateData['date']] += $dateData['confirmed'];
    }
}

Update:

For the new format, you just need to extract the data from the array so far...

$output = ["date" => array_keys($confirmed_array),
    "total_confirmed" => array_values($confirmed_array),
    "max_value_of_total_confirmed" => max($confirmed_array)
];
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your help, it works!!!! but could you please see my updated post? :)
Hi Nigel, I wonder is it possible to grouping those data by week (not a day)? something like W1 Jan, W2 Jan, W3 Jan, etc?
It may be worth asking a new question for this.
Hi Nigel, could you please help me to get the same result as my updated post, but with this kind of json: corona.lmao.ninja/v2/historical ? been trying for 2 days and I still didn't understand how to count inside loop array :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.