Jack
Jack

Reputation: 3057

Target the last list in JSON array

{
  events: [
    {
      event: {
      status: "Completed",
      title: "Roy Smoothe Talk: CEO of 'Just Cool'",
      url: "https://brookesbe.eventbrite.co.uk/?ref=ebapi",
      id: 10487792269,
      repeats: "no",
      start_date: "2014-03-03 18:00:00"
      }
    },
      {
      event: {
      status: "Live",
      title: "Brookes Entrepreneurs Speed Networking Event",
      url: "https://www.eventbrite.co.uk/e/brookes-entrepreneurs-speed-networking-event-tickets-10841927497?ref=ebapi",
      id: 10841927497,
      repeats: "no",
      start_date: "2014-03-24 18:00:00"
      }
    }
  ]
}

Should this be hard to understand live can be seen here

I've had a look at this question

get last element of a json object in javascript

Although I cannot see how to apply it to my question.

I am currently using this code to fetch the second item which works but will break when a new event is added.

function eb_widget($ret){
  $obj = my_cache_user_list_events();
  if ($ret == "title") {
    return  ($obj->events[1]->event->title);
  }
  if ($ret == "url") {
    return  ($obj->events[1]->event->url);
  } 
  if ($ret == "start_date") {
    return  ($obj->events[1]->event->start_date);
  }
  if ($ret == "status"){
    return ($obj->events[1]->event->status);
  }
}

I tried to use [-1] although that does not seem to work. What I think I need to do is count the number of "events" then use length -1 although I do not know how to do this.

Thanks

Upvotes: 1

Views: 157

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 79024

This:

return end($obj->events)->event->title;

Or this:

$last = end($obj->events);
return $last->event->title;

Upvotes: 3

The end keyword as answered is the way to go, but you could also do it like this:

$obj->events[count($obj->events) - 1]

Fiddle example

Upvotes: 0

Related Questions