0

So got a slight problem that I've tried my best to solve but without success. I have a Facebook app that accesses checkin information and as such goes through the API which produces the JSON output in a multi-dimensional array. I'm coding in PHP.

Problem I've got is not every checkin has the coordinate/location information (latitude / longitude) so it will come back with an error on the page.

I want to go through the array of information and find out if the key exists and/or if there is any information contained within it.

foreach ($checkins['data'] as $checkin) {
      echo ("<p>{$checkin['place']['location']['latitude']}</p>");
      echo ("<p>{$checkin['place']['location']['longitude']}</p>");
}

That is the code I use but like I say if there isn't any location information I get an error. Does anyone know how I could solve this issue or is there an easy way of looping through and finding out if the specific keys exist?

Any help would be much appreciated!

Thank you!

2 Answers 2

1

Check if the content you're looking for exists with isset():

foreach ($checkins['data'] as $checkin) {
      if(isset($checkin['place']) 
         && isset($checkin['place']['location'])
         && isset($checkin['place']['location']['latitude'])
         && isset($checkin['place']['location']['longitude'])
      ) {
           echo ("<p>{$checkin['place']['location']['latitude']}</p>");
           echo ("<p>{$checkin['place']['location']['longitude']}</p>");
      }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

foreach ($checkins['data'] as $checkin) {
     if ( array_key_exists( 'place', $checkin ) &&
          array_key_exists( 'location', $checkin['place'] ) &&
          array_key_exists( 'latitude', $checkin['place']['location'] ) &&
          array_key_exists( 'longitude', $checkin['place']['location'] )
        ) 
     {
         echo ("<p>{$checkin['place']['location']['latitude']}</p>");
         echo ("<p>{$checkin['place']['location']['longitude']}</p>");
    }
}

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.