How to deal with JSON output that might be an array, or might be a value
- by Summer
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?