How to deal with JSON output that might be an array, or might be a value

Posted by Summer on Stack Overflow See other posts from Stack Overflow or by Summer
Published on 2010-04-26T15:42:27Z Indexed on 2010/04/26 15:43 UTC
Read the original article Hit count: 241

Filed under:
|
|

Hi -

I'm getting JSON-encoded output from another organization's API.

In many cases, the output can be either an array of objects (if there are many) or an object (if there's just one). Right now I'm writing tortured code like this:

if ( is_array($json['candidateList']['candidate'][0]) ) {
  foreach ($json['candidateList']['candidate'] as $candidate) {
    // do something to each object
  }
}
else {
  // do something to the single object
}

How can I handle it so the "do something" part of my code only appears once and uses a standard syntax?

© Stack Overflow or respective owner

Related posts about php

Related posts about JSON