Wolvy
Wolvy

Reputation: 141

How to get last value from a json in php

I have problem with a json, this json keeps updating, so the last entry will never be the same. This is the json:

{"channel":{"id":274304,"name":"Water","description":"Record water consumption.","latitude":"0.0","longitude":"0.0","field1":"Water","created_at":"2017-05-17T16:27:46Z","updated_at":"2017-05-19T01:01:07Z","last_entry_id":28},"feeds":[{"created_at":"2017-05-19T00:51:35Z","entry_id":1,"field1":"288"},{"created_at":"2017-05-19T00:51:50Z","entry_id":2,"field1":"304"}]}

I have something like this in my php code, where the variable $cool contains the decoded json.

$x= $cool->feeds[2]->field1;

But when the json updates, feeds[2] will not be the last entry. So i was thinking of using arrays to store all data. But i don't know how to do this. Can you help me?

Upvotes: 1

Views: 4967

Answers (2)

LF-DevJourney
LF-DevJourney

Reputation: 28564

If you want to get the last element, you also can use array_pop()

$x = array_pop($cool->feeds)->field1;

Upvotes: 0

deceze
deceze

Reputation: 522626

If $cool->feeds is an array as I assume, you can use end to get its last item:

$x = end($cool->feeds)->field1;

Upvotes: 4

Related Questions