-2

I have an API from a .json url that gives me an ID, the distance, and the duration in HH:MM format.

[
    {
        "id": "210",
        "distance": "299",
        "duration": "01:31"
    },
    {
        "id": "209",
        "distance": "279",
        "duration": "01:22"
    },
    {
        "id": "209",
        "distance": "261",
        "duration": "01:15"
    }
]

I'd like to make the sum of an ID's duration so that here 01:22 + 01:15 would give me 02:37 but I have no idea how to do that.

Any help ?

Thanks,
Snax

Snax
  • 1
  • 1

1 Answers1

0

You can use strtotime to do the addition part of the problem - firstly though you decode the data and iterate through it, like this:

$json=json_decode('[
    {
        "id": "210",
        "distance": "299",
        "duration": "01:31"
    },
    {
        "id": "209",
        "distance": "279",
        "duration": "01:22"
    },
    {
        "id": "209",
        "distance": "261",
        "duration": "01:15"
    }
]');

$t=0;
foreach( $json as $obj )$t+=strtotime( $obj->duration );
echo date( 'H:i', $t );

Result:

04:08
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • I'll give it a try, thanks for your input. – Snax Nov 20 '19 at 20:44
  • Hi again, following your example, I tried this: ```$t = 0; foreach($json as $obj) { if($obj->id == '209') { $t+=strtotime($obj->duration); print_r(date('H:i', $t)); } }``` The result is that I only had the first key shown (1:22), and the following warning: **Warning**: date() expects parameter 2 to be int, float given in /www/hours.php on line 25 Any idea why it doesn't work ? – Snax Nov 20 '19 at 21:41