How to deal with JSON output that might be an array, or might be a value
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?
Just make it an array if it's not - then proceed with the iteration.
// Normalize response into an array
if ( !is_array( $json['candidateList']['candidate'] ) )
{
$json['candidateList']['candidate'] = array( $json['candidateList']['candidate'] );
}
// Process data
foreach ($json['candidateList']['candidate'] as $candidate) {
// do something to each object
}
You should tell whoever is providing the feed that it should be more consistent :) in this case, it would be appropriate always to have an array, even if there is only one candidate, so you would have just one-element array.
<?php
// When json is an object, convert to an array with a single member
if (is_object($json)) $json = array($json);
foreach ($json as $object) {
// do something to each object
}
Put the "do something" code in a function, and then call the function from both places. This has the side-benefit of modularizing your code.
Alternately, you can detect you only have a single element and build an array around it, then use your array-handling code in both places.
(Side note: I agree with Jaanus. A well-formed API would return a list in both cases, even if the list is only one member long. For exactly this reason.)
If you can get the api changed, go with Jaanus' answer. Otherwise, maybe write a function that takes a value and returns either the value (if the value is an array) or a one-element array containing the value (if it is not).
精彩评论