1
{
  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

Community
  • 1
  • 1
Jack
  • 2,891
  • 11
  • 48
  • 65
  • 2
    This is not valid JSON. Keys must be strings. – Felix Kling Mar 08 '14 at 17:45
  • Sorry I don't understand. I found it hard to fully copy paste the JSON so I had to indent it my self and may have missed some stuff out. – Jack Mar 08 '14 at 20:45
  • Valid JSON is `{"events": [...]}`, whereas you have `{events: [...]}`. I just wanted to make sure that you really have JSON. It's often difficult to focus on the actual issue if you introduced errors by pasting code here (i.e. those errors are not in your actual code). – Felix Kling Mar 08 '14 at 20:55

2 Answers2

3

This:

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

Or this:

$last = end($obj->events);
return $last->event->title;
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

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

Hein Andre Grønnestad
  • 6,885
  • 2
  • 31
  • 43