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

3
  • 2
    This is not valid JSON. Keys must be strings. Commented Mar 8, 2014 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. Commented Mar 8, 2014 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). Commented Mar 8, 2014 at 20:55

2 Answers 2

3

This:

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

Or this:

$last = end($obj->events);
return $last->event->title;
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, didn't now about the end keyword.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.