-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

1

1 Answer 1

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

2 Comments

I'll give it a try, thanks for your input.
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 ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.